var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/functionalComponent/table/index.tsx
var table_exports = {};
__export(table_exports, {
  Table: () => Table,
  TableSelectionModel: () => import_common.TableSelectionModel,
  TableSymbol: () => TableSymbol
});
module.exports = __toCommonJS(table_exports);
var import_icons = require("@ant-design/icons");
var import_antd = require("antd");
var import_react = __toESM(require("react"));
var import_react_dom = __toESM(require("react-dom"));
var import_widgets = require("../../widgets");
var import_message = require("../antd/message");
var import_common = require("./base/common");
var import_alert = require("./child/alert");
var import_body = require("./child/body");
var import_check = require("./child/check");
var import_expand = require("./child/expand");
var import_header = require("./child/header");
var import_pagination = require("./child/pagination");
var import_factory = require("./editor/factory");
var import_index = require("./index.less");
var import_util = require("./util");
var TREE_LEVEL = Symbol("__treeLevel");
var TREE_INDEX = Symbol("__treeIndex");
var TREE_LAST_CHILD = Symbol("__treeLastChild");
var TREE_LEAF_NODE = Symbol("__treeLeafNode");
var TREE_PARENT = Symbol("__treeParent");
var GROUP_PARENT = Symbol("__groupParent");
var DEFAULT_CHECKED = Symbol("__defaultChecked");
var ROW_KEY_FIELD = Symbol("__id");
var TableSymbol = { TREE_LEVEL, TREE_INDEX, TREE_LAST_CHILD, TREE_PARENT, GROUP_PARENT, TREE_LEAF_NODE };
function updateTreeSymbol({ parentNode, node, index, level, isLeaf }) {
  node[TREE_LEVEL] = level;
  node[TREE_INDEX] = index;
  node[TREE_PARENT] = parentNode;
  node[TREE_LEAF_NODE] = isLeaf;
}
var TableGrid = import_react.default.memo(
  ({ table, columns }) => {
    const providerValue = (0, import_react.useMemo)(() => {
      return { table, columns };
    }, [columns]);
    (0, import_react.useEffect)(() => {
      var _a;
      const rows = table.store.data;
      if (table.props.dataSource && table.props.dataSource !== rows) {
        table.props.dataSource.splice(0, table.props.dataSource.length, ...rows);
      }
      if (table.dsUpdateCallback) {
        table.dsUpdateCallback(table);
        table.dsUpdateCallback = void 0;
      }
      if (!((_a = table.state.dataSource) == null ? void 0 : _a.length)) {
        table._lastHighlightRowIndex = -1;
        table._updateSubTable(null).then();
      }
      if (table.lastUpdateFlag !== import_common.UpdateFlagEnum.ColumnChecked) {
        table.notify({ updateRow: rows, table: void 0 }, "onUpdateRows");
      }
    }, [table.state.dataSource]);
    if (table.state.width > 0) {
      return /* @__PURE__ */ import_react.default.createElement(import_common.TableContext.Provider, { value: providerValue }, /* @__PURE__ */ import_react.default.createElement(import_common.DsContext.Provider, { value: table.state.dataSource }, /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          style: {
            display: "flex",
            flexDirection: "column",
            position: "relative",
            zIndex: 1
          }
        },
        table.alertObj.container && import_react_dom.default.createPortal(/* @__PURE__ */ import_react.default.createElement(import_alert.TableAlert, { key: "alert", table }), table.alertObj.container),
        /* @__PURE__ */ import_react.default.createElement(import_header.TableHeader, { key: "header" }),
        /* @__PURE__ */ import_react.default.createElement("div", { key: "content", style: { flex: 1, zIndex: 1, overflow: "hidden" } }, /* @__PURE__ */ import_react.default.createElement(import_body.TableBody, null)),
        table.props.pagination && /* @__PURE__ */ import_react.default.createElement(import_pagination.TablePagination, { key: "footer", table })
      )));
    }
    return /* @__PURE__ */ import_react.default.createElement("div", { style: { height: "100%" } });
  },
  (p, n) => {
    if (n.table.updateFlag !== import_common.UpdateFlagEnum.None) {
      return false;
    }
    return import_util.util.isPropsEqual(p, n, { shallow: true, exclude: ["table", "props", "state"] }) && import_util.util.isPropsEqual(p.state, n.state, {
      shallow: true,
      exclude: ["loading", "columns", "props", "changedFields"]
    }) && import_util.util.isPropsEqual(p.props, n.props, {
      shallow: true,
      exclude: [
        "local",
        "optimize",
        "expandCfg",
        "cache",
        "pagination",
        "request",
        "onDataLoad",
        "response",
        "loading",
        "onRow",
        "rowFilter",
        "rowContextMenu",
        "bodyContextMenu",
        "expandRow",
        "onCheckedChange",
        "rowSelection"
      ]
    });
  }
);
var defaultProps = {
  /**
   * @description       紧凑表格
   * @default           false
   */
  compact: false,
  /**
   * @description       表格延迟resize的毫秒数
   * @default           16
   */
  resizeDelay: 16,
  /**
   * @description       是否加载中
   * @default           false
   */
  loading: false,
  /**
   * @description       配置request属性，是否自动加载数据
   * @default           true
   */
  autoLoad: true,
  /**
   * @description       是否树形列表
   * @default           false
   */
  isTree: false,
  /**
   * @description       是否显示单元格边框
   * @default           false
   */
  bordered: false,
  /**
   * @description       是否隐藏表头
   * @default           false
   */
  hiddenHeader: false,
  /**
   * @description       是否支持单击行选中checkbox
   * @default           false
   */
  rowChecked: false,
  /**
   * @description       点击数据行高亮选中行
   * @default           true
   */
  rowSelected: true,
  /**
   * @description       点击checkbox列高亮选中行
   * @default           false
   */
  checkboxSelected: false,
  /**
   * @description       是否启用虚拟滚动，建议开启；如果需要高度随内容自动撑开，设置false
   * @default           true
   */
  virtualScrolling: true,
  /**
   * @description       编辑状态，是否支持最后一行按"下方向键"及最后一列按"回车"或"tab"自动增加行
   * @default           false
   */
  keyBoardToAddRow: false,
  /**
   * @description       编辑状态，键盘事件的是否绑定在document上，注意多个Grid会产生冲突
   * @default           false
   */
  listenerOnDocument: false,
  /**
   * @description       是否开启记忆列状态功能
   * @default           true
   */
  remember: true
};
var TableClass = class extends import_util.IUPComponent {
  // 构造函数
  constructor(props) {
    super(props);
    this.containerRef = import_react.default.createRef();
    this.headerRef = import_react.default.createRef();
    this.bodyRef = import_react.default.createRef();
    this.alertObj = { container: null };
    this.showEditor = ["checkbox", "switch", "radiogroup", "checkboxgroup", "attachment"];
    this.headerHeight = 0;
    this.groupColumns = { left: [], normal: [], right: [] };
    this.groupDs = [];
    this.unmount = false;
    this._lastHighlightRowIndex = -1;
    this.lastHighlightKey = void 0;
    this.updateFlag = import_common.UpdateFlagEnum.None;
    this.lastUpdateFlag = import_common.UpdateFlagEnum.None;
    this.currentUpdateRow = null;
    // 缓存前端分页的请求数据
    this._isPagination = false;
    // 分页操作
    this._lockEdit = false;
    // 锁定编辑状态，防止自动取消编辑
    this.cellStyle = {};
    // 单元格公共样式
    this.expandColumn = null;
    this.dataIndexMap = {};
    this.expandLevel = 0;
    this.rawData = [];
    this._expandedKeys = /* @__PURE__ */ new Set();
    // 展开行的key值
    this._selectedKeys = /* @__PURE__ */ new Set();
    this._keyMap = /* @__PURE__ */ new Map();
    this.parentInfo = void 0;
    this._lastParentRow = null;
    this._updateSubTable = async (row) => {
      const subTable = this.props.subTable;
      if (subTable && this._lastParentRow !== row) {
        this._lastParentRow = row;
        const ids = Object.keys(subTable);
        const promiseArray = ids.map((id) => {
          const [subDataField, subDataFunction] = subTable[id].dataSource;
          const fn = async () => {
            if (row && subDataFunction) {
              row[subDataField] = await subDataFunction(row);
            }
            return [subDataField, (row == null ? void 0 : row[subDataField]) || []];
          };
          return fn();
        });
        const subTableData = await Promise.all(promiseArray);
        subTableData.forEach(([key, data], idx) => {
          var _a;
          const id = ids[idx];
          (_a = import_util.util.getCmpApi(id)) == null ? void 0 : _a.setSubDataSource(data, { data: row, key });
        });
      }
    };
    this._defaultDs = Promise.resolve([]);
    this._getCellPadding = () => {
      return this.props.compact ? 2 : 6;
    };
    this._onBeforeResize = ({ width }) => {
      var _a;
      if (((_a = this.outRef.current) == null ? void 0 : _a._outerRef) && width > this.state.width) {
        this.outRef.current._outerRef.style.overflow = "visible";
      }
    };
    this._onResize = (wh, options = {}) => {
      var _a;
      const { flushSync = false } = options;
      if (wh.width !== this.state.width || wh.height !== this.state.height) {
        const updateState = (state) => {
          flushSync ? import_react_dom.default.flushSync(() => {
            this.setState(state);
          }) : this.setState(state);
        };
        const minHeight = ((_a = this.props.style) == null ? void 0 : _a.minHeight) || 0;
        if (wh.height > minHeight) {
          updateState(wh);
        } else if (wh.width !== this.state.width) {
          updateState({ width: wh.width });
        }
      }
    };
    this._onRootElementClick = () => {
      if (this.state.selected.editing && this.props.autoCancelEditor !== false && !this._lockEdit) {
        this.endEditing(true, false);
      }
    };
    const { dataSource, optimize = {}, stateId, rowFilter } = props;
    const copyData = dataSource ? this.deepCopyRaw(dataSource) : this._defaultDs;
    this._observer = props.observer || new import_util.Observer();
    this.uniqueId = `${import_util.util.getHistory().location.pathname || window.location.hash || window.location.pathname}-${this.getId()}`;
    this.stateId = stateId || this.uniqueId;
    this._rowFilter = import_util.util.isFunction(rowFilter) ? rowFilter : null;
    this.store = {
      raw: copyData,
      data: dataSource || [],
      aggregateData: dataSource || []
    };
    this.state = {
      props,
      vertical: !!optimize.vertical,
      changedFields: [],
      updateTime: 0,
      width: 0,
      height: 0,
      loading: props.loading ?? props.defaultLoading,
      errors: {},
      params: {
        ...this._getDefaultPagination()
      },
      currentExpandRow: null,
      dataSource: [],
      orderBy: [],
      columns: this._loadColumnState(props.columns || [], true),
      selected: { rowIndex: -1, dataIndex: null, editing: false }
    };
    this.state.dataSource = this.generateDataSource(this.store.data, {});
    this._initDefaultSelected(this.state.dataSource);
    this.subscribe((activeEditor) => {
      this._activeEditor = activeEditor;
    }, "activeEditor");
  }
  setReadOnly(readOnly = true) {
    var _a;
    (_a = this._compIns) == null ? void 0 : _a.setProps({ readOnly });
  }
  getObj() {
    return this.alertObj;
  }
  getTableSymbol() {
    return TableSymbol;
  }
  _isCacheKey(key) {
    const cache = this.props.cache;
    return import_util.util.isArray(cache) && cache.includes(key);
  }
  _setKeyMap(row, del = false) {
    const key = row[this.getKeyField()];
    if (del) {
      this._keyMap.delete(key);
      this._selectedKeys.delete(key);
    } else {
      this._keyMap.set(key, row);
    }
  }
  _setExpandedKeys(row, index) {
    const { groupBy, keyField } = this.props;
    if (!keyField) {
      return;
    }
    let keyV = groupBy ? row[groupBy] : row[keyField];
    const expanded = row[this.getExpandField()];
    if (expanded && keyV === void 0 && !groupBy) {
      keyV = import_util.util.uniqueId(index) + "_$_";
      row[keyField] = keyV;
    }
    if (expanded) {
      this._expandedKeys.add(keyV);
    } else if (this._expandedKeys.has(keyV)) {
      this._expandedKeys.delete(keyV);
    }
  }
  _updateParentInfo(rows) {
    if (this.parentInfo) {
      const { data, key } = this.parentInfo;
      data && (data[key] = rows);
    }
  }
  /**
   * 列分组格式化
   * @private
   */
  _initColumns(originColumns, initPropsColumn) {
    const allCol = [[], [], []];
    const { dataIndexProps = {}, columns: propColumns, columnSort, tooltip, headerTooltip } = this.props;
    const columns = originColumns || propColumns;
    const fn = (cols, groups, parentProps) => {
      cols.forEach((c) => {
        const getCol = () => {
          if (initPropsColumn) {
            c.propHidden = !!c.hidden;
          }
          if (c.dataIndex) {
            const dip = import_util.util.isFunction(dataIndexProps) ? dataIndexProps : dataIndexProps[c.dataIndex];
            const dp = import_util.util.isFunction(dip) ? dip(c) : dip;
            if (dp == null ? void 0 : dp.editor) {
              dp.editor = { ...c.editor, ...dp.editor };
            }
            const nCol = { ...c, ...dp };
            nCol.header = (0, import_util.getColumnHeader)(nCol);
            if (nCol.editor) {
              const outProps = {};
              c.hasOwnProperty("disabled") && (outProps.disabled = c.disabled);
              c.hasOwnProperty("required") && (outProps.required = c.required);
              nCol.editor = { ...outProps, ...nCol.editor };
            }
            return nCol;
          }
          return { ...c, header: (0, import_util.getColumnHeader)(c) };
        };
        const column = getCol();
        const { columns: columns2, children, dataIndex, editor, ...others } = column;
        const childrenColumns = columns2 || children || [];
        if (childrenColumns.length) {
          fn(childrenColumns, [...groups, column.header || parentProps.header], {
            ...parentProps,
            ...others
          });
        } else {
          if (groups.length) {
            column.groupIn = groups;
          }
          if (column.groupIn && !import_util.util.isArray(column.groupIn)) {
            column.groupIn = [column.groupIn];
          }
          const tmp = { ...parentProps, ...column };
          const pos = tmp.fixed ? tmp.fixed === "right" ? 2 : 0 : 1;
          allCol[pos].push(tmp);
        }
      });
    };
    fn(columns, [], {
      sortable: true,
      resizable: true,
      tooltip: tooltip ?? false,
      headerTooltip: headerTooltip ?? false,
      columnSort: columnSort ?? true
    });
    return import_util.util.flatArray(allCol);
  }
  /**
   * 加载columns的状态
   */
  _loadColumnState(columns, initPropsColumn = false) {
    const columnState = this.getColumnState();
    if (columnState) {
      const fn = (newColumns) => {
        return newColumns.map((column) => {
          var _a;
          if (initPropsColumn) {
            column.propHidden = !!column.hidden;
          }
          const columns2 = column.columns || column.children || [];
          if (columns2.length > 0) {
            column.columns = fn(columns2);
            return column;
          } else if (column.dataIndex) {
            const idx = ((_a = columnState[column.dataIndex]) == null ? void 0 : _a.idx) ?? 999999;
            return { ...column, ...columnState[column.dataIndex], idx };
          } else {
            return column;
          }
        }).sort((a, b) => a.idx - b.idx);
      };
      columns = fn(columns);
      initPropsColumn = false;
    }
    return this._initColumns(columns, initPropsColumn);
  }
  /**
   * 保存columns的状态
   */
  _saveColumnState() {
    const columnState = {};
    const fn = (stateColumns) => {
      stateColumns.forEach(({ dataIndex, width, hidden, columns, fixed }, idx) => {
        if (columns && columns.length > 0) {
          fn(columns);
        } else if (dataIndex) {
          columnState[dataIndex] = { width, hidden, idx, fixed };
        }
      });
    };
    fn(this.state.columns);
    if (this.props.columnStateChange) {
      this.props.columnStateChange({
        key: this.stateId,
        columnState
      });
    } else if (this.props.remember) {
      import_util.util.setCache(this.stateId, columnState);
    }
  }
  _initDefaultSelected(dataSource) {
    var _a;
    let cacheRowIndex;
    const cacheKey = `${this.uniqueId}_selected`;
    if (this._isCacheKey("selected") && dataSource.length) {
      const obj = import_util.util.getCache(cacheKey, { type: "session", toObject: true }) || {};
      cacheRowIndex = obj.highlight;
      (_a = obj.selected) == null ? void 0 : _a.forEach((i) => {
        const r = dataSource[i];
        if (this.props.checkbox) {
          r[this.getCheckBoxDataIndex()] = true;
        }
        this._selectedKeys.add(r[this.getKeyField()]);
      });
      import_util.util.removeCache(cacheKey, { type: "session" });
    }
    const getLastRowIndexByKey = () => {
      const { keyField } = this.props;
      if (this.lastHighlightKey && keyField) {
        for (let i = 0, len = dataSource.length; i < len; i++) {
          if (dataSource[i][keyField] === this.lastHighlightKey) {
            return i;
          }
        }
      }
      return void 0;
    };
    const defaultSelectedRowIndex = cacheRowIndex ?? getLastRowIndexByKey() ?? this.props.defaultSelectedRowIndex;
    if (!import_util.util.isNullOrEmpty(defaultSelectedRowIndex)) {
      this._lastHighlightRowIndex = import_util.util.isFunction(defaultSelectedRowIndex) ? defaultSelectedRowIndex(dataSource) : Number(defaultSelectedRowIndex);
    }
  }
  _getDefaultPagination() {
    const { pagination } = this.props;
    if (!pagination) {
      return {};
    }
    if (this._isCacheKey("page")) {
      const cacheObj = import_util.util.getCache(`${this.uniqueId}_page`, { type: "session", toObject: true });
      if (cacheObj) {
        return {
          pageIndex: cacheObj.pageIndex ?? 1,
          pageSize: cacheObj.pageSize ?? 15
        };
      }
    }
    return {
      pageIndex: pagination.pageIndex ?? 1,
      pageSize: pagination.pageSize ?? 15
    };
  }
  _generateGroupDs(ds, parent, groupIndex) {
    const { groupAggregatePosition } = this.props;
    ds.push(parent);
    let insertIndex = ds.length;
    if (parent[this.getExpandField()]) {
      parent.children.forEach((r) => ds.push(r));
      if (groupAggregatePosition === "end") {
        insertIndex = ds.length;
      }
      if (this.generateColumns().aggregates.length > 0) {
        ds.splice(insertIndex, 0, {
          cellType: import_common.CellTypeEnum.AggregateCell,
          parent,
          groupIndex
        });
      }
    }
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    const stateFromPropKeys = {
      convert: ["dataSource", "columns"],
      normal: ["loading"]
    };
    let hasChanged = false;
    const updateState = {
      props: { ...prevState.props },
      changedFields: []
    };
    stateFromPropKeys.convert.forEach((key) => {
      if (nextProps[key] !== prevState.props[key]) {
        updateState.props[key] = nextProps[key];
        updateState.changedFields.push(key);
        hasChanged = true;
      }
    });
    stateFromPropKeys.normal.forEach((key) => {
      if (nextProps[key] !== prevState.props[key]) {
        updateState.props[key] = nextProps[key];
        updateState[key] = nextProps[key];
        hasChanged = true;
      }
    });
    return hasChanged ? updateState : null;
  }
  /**
   * 发布通知消息
   */
  notify(value, type) {
    const containerId = this.getId(false);
    if (containerId) {
      import_util.util.getPageObserver().notify(
        {
          key: containerId,
          containerId,
          instance: this,
          table: this,
          args: [(value == null ? void 0 : value.updateRow) || {}, value]
        },
        type
      );
    }
    if (type === "onUpdateRow") {
      if (value == null ? void 0 : value.dataIndex) {
        import_util.util.getPageObserver().notify(
          {
            key: value.dataIndex,
            containerId,
            instance: this,
            table: this,
            args: [value.updateRow || {}, value]
          },
          "onDataIndexChange"
        );
      }
      this._observer.notify(value, "updateRow");
      return this._observer.notify(value, "onUpdateRow");
    }
    return this._observer.notify(value, type);
  }
  /**
   * 订阅消息
   * @param fn
   * @param notifyType
   */
  subscribe(fn, notifyType) {
    return this._observer.subscribe(fn, notifyType);
  }
  /**
   * 获取columns的状态
   */
  getColumnState() {
    return this.props.remember ? import_util.util.getCache(this.stateId, true) : void 0;
  }
  getGroupColumns(columns, type) {
    const newColumns = [];
    this.groupColumns[type] = [];
    const getChildren = (c, index) => {
      if (c.groupIn[index]) {
        return [
          {
            groupTitle: c.groupIn[index],
            children: getChildren(c, index + 1)
          }
        ];
      } else {
        return [c];
      }
    };
    const findGroup = (arr, c, index) => {
      const groupIn = c.groupIn;
      const find = arr.find(({ groupTitle }) => groupTitle === groupIn[index]);
      if (find) {
        if (groupIn.length > index + 1) {
          findGroup(find.children, c, index + 1);
        } else {
          find.children.push(c);
        }
      } else {
        arr.push({
          groupTitle: groupIn[index],
          children: getChildren(c, index + 1)
        });
      }
    };
    columns.forEach((c) => {
      if (c.groupIn) {
        findGroup(this.groupColumns[type], c, 0);
      } else {
        this.groupColumns[type].push(c);
      }
    });
    const pushColumn = (g) => {
      if (g.children) {
        g.children.forEach((c) => pushColumn(c));
      } else {
        newColumns.push(g);
      }
    };
    this.groupColumns[type].forEach((g) => pushColumn(g));
    return newColumns;
  }
  getDataIndexMap() {
    return this.dataIndexMap;
  }
  /**
   * 重置行高，行高根据内容自适应
   * @param rowIndex 刷新的起始索引位置
   * @param immediate 立即刷新
   */
  _resetRowHeight({ rowIndex, immediate = true }) {
    var _a;
    const { rowHeight } = this.props;
    if (this.shouldResetStyleCacheOnItemSizeChange() || rowHeight === "auto" || import_util.util.isFunction(rowHeight)) {
      rowIndex = rowIndex ?? this.getRenderRange().rowIndex[0];
      (_a = this.outRef.current) == null ? void 0 : _a.resetAfterRowIndex(rowIndex, false);
      if (immediate) {
        this.refreshView();
      }
    }
  }
  proxyUpdateRow(row) {
    return new Proxy(row, {
      set(target, key, value) {
        target.__update__ = {};
        return Reflect.set(target, key, value);
      }
    });
  }
  updateChildren(row, todo, updateView = false) {
    import_util.util.loopChildren(row, (r) => {
      return todo(this.proxyUpdateRow(r));
    });
    updateView && this.setDataSource([...this.state.dataSource], { updateRaw: false, udpateStore: false });
  }
  updateParent(row, todo, updateView = false) {
    const loop = (data, todo2) => {
      const r = data[TREE_PARENT];
      if (!r) {
        return;
      }
      if (todo2(this.proxyUpdateRow(r)) === false) {
        return;
      }
      loop(r, todo2);
    };
    loop(row, todo);
    updateView && this.setDataSource([...this.state.dataSource], { updateRaw: false, udpateStore: false });
  }
  /**
   * 展开树层级
   * @param level
   * @param strictly 严格按照level展开树节点
   */
  expandTree(level, strictly = true) {
    var _a;
    if (!this.props.isTree || level < 0) {
      return;
    }
    const rowIndex = this.getRenderRange().rowIndex[0];
    (_a = this.outRef.current) == null ? void 0 : _a.resetAfterRowIndex(rowIndex, false);
    this.refreshView({
      state: {
        dataSource: this.generateDataSource(this.store.data, { level, strictly })
      }
    });
  }
  generateColumns() {
    var _a;
    if (!this.cacheColumns) {
      const offsetWidth = this.state.width - (this.state.vertical ? (0, import_util.getScrollBarInfo)().width : 0);
      const variable = {
        totalColumnWidth: 0,
        headerLine: 1,
        usedWidth: 0,
        totalFlex: 0,
        aggregates: [],
        columnSort: false,
        groupable: false,
        useFlex: false,
        dataIndexExpr: [],
        summaryCols: []
      };
      const editableColumnIndex = [];
      const unsetWidthColumns = [];
      const columnIndex = { left: 0, right: 0, normal: 0 };
      const allColumns = this.state.columns;
      const { checkbox, showRowNumber = false, expandRow, isTree = false, align, compact, expandCfg = {} } = this.props;
      this._resetRowHeight({ immediate: false });
      const { dataIndex: expandCfgDataIndex, icon, fixed, width: expandWidth, showLine, block = true } = expandCfg;
      const expandIconWidth = Math.max(0, expandWidth ?? 24);
      const cellPadding = this._getCellPadding();
      const leftFixedColumns = [];
      const tableIns = this;
      if (expandRow && !expandCfgDataIndex || this.groupByColumn) {
        leftFixedColumns.push({
          header: () => void 0,
          width: expandIconWidth,
          columnIndex: columnIndex.left++,
          render: ({ rowIndex }) => {
            const row = this.getRow(rowIndex);
            if (expandIconWidth === 0 || this.groupByColumn && !row[import_common.IS_GROUP]) {
              return null;
            }
            return /* @__PURE__ */ import_react.default.createElement(import_expand.ExpandIcon, { row, table: tableIns, rowIndex, icon });
          }
        });
        variable.usedWidth += expandIconWidth;
      }
      if (checkbox) {
        leftFixedColumns.push({
          header: () => /* @__PURE__ */ import_react.default.createElement(import_check.AllCheckBox, { table: tableIns }),
          width: 34,
          columnIndex: columnIndex.left++,
          dataIndex: this.getCheckBoxDataIndex(),
          render: ({ rowIndex, dataIndex }) => {
            return /* @__PURE__ */ import_react.default.createElement(import_check.RowCheckBox, { table: tableIns, dataIndex, row: this.getRow(rowIndex), rowIndex });
          }
        });
        variable.usedWidth += 34;
      }
      if (showRowNumber) {
        const cfg = { title: "行号", width: 43, dataIndex: "_number_index_" };
        let opt;
        if (import_util.util.isObject(showRowNumber)) {
          const { editOptions, ..._cfg } = showRowNumber;
          if (editOptions) {
            cfg.width = 52;
            opt = editOptions;
          }
          import_util.util.assign(cfg, _cfg);
        }
        leftFixedColumns.push({
          ...cfg,
          columnIndex: columnIndex.left++,
          headerStyle: { textAlign: "center", ...cfg.headerStyle },
          cellStyle: { textAlign: "center", ...cfg.cellStyle },
          render: (param) => {
            var _a2, _b, _c;
            const { row, rowIndex, pageIndex = 1, pageSize = 15 } = param;
            const index = cfg.render ? cfg.render(param) : import_util.util.isNullOrEmpty(row["__index__"]) ? `${pageSize * (pageIndex - 1) + rowIndex + 1}` : row["__index__"];
            const [add, del] = [
              (e) => {
                e.stopPropagation();
                if (opt == null ? void 0 : opt.add) {
                  opt == null ? void 0 : opt.add({ table: this, rowIndex });
                } else {
                  this.addRows({}, rowIndex + 1);
                }
              },
              (e) => {
                e.stopPropagation();
                if (opt == null ? void 0 : opt.delete) {
                  opt == null ? void 0 : opt.delete({ table: this, rowIndex });
                } else {
                  this.deleteRows(rowIndex);
                }
              }
            ];
            const disableKeys = import_util.util.isBoolean(opt == null ? void 0 : opt.disabled) ? opt.disabled : (_a2 = opt == null ? void 0 : opt.disabled) == null ? void 0 : _a2.call(opt, { table: this, rowIndex });
            const disableAdd = disableKeys === true || ((_b = disableKeys == null ? void 0 : disableKeys.includes) == null ? void 0 : _b.call(disableKeys, "add"));
            const disableDel = disableKeys === true || ((_c = disableKeys == null ? void 0 : disableKeys.includes) == null ? void 0 : _c.call(disableKeys, "delete"));
            const hasBtn = !!opt && !(disableAdd && disableDel);
            return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("span", { className: import_util.util.classNames("nowrap", { "rn-index": hasBtn }) }, index), hasBtn && /* @__PURE__ */ import_react.default.createElement("div", { className: "rn-op" }, /* @__PURE__ */ import_react.default.createElement("a", { onClick: add, hidden: disableAdd }, /* @__PURE__ */ import_react.default.createElement(import_icons.PlusCircleFilled, null)), /* @__PURE__ */ import_react.default.createElement("a", { onClick: del, hidden: disableDel, style: { color: "red", marginLeft: 6 } }, /* @__PURE__ */ import_react.default.createElement(import_icons.MinusCircleFilled, null))));
          }
        });
        variable.usedWidth += cfg.width;
      }
      variable.totalColumnWidth = variable.usedWidth;
      const normalColumns = [];
      const rightFixedColumns = [];
      this.expandColumn = null;
      this.dataIndexMap = {};
      let expandDataIndex = expandCfgDataIndex;
      allColumns.forEach((column, index) => {
        var _a2, _b, _c;
        if (column.dataIndex) {
          if (column.expr) {
            const exprType = import_util.util.isFunction(column.expr) ? "function" : "string";
            variable.dataIndexExpr.push({
              exprType,
              dIdx: column.dataIndex,
              expr: column.expr,
              fn: exprType === "function" ? column.expr : new Function("$R", "$D", "$V", "$DI", `return ${column.expr}`)
            });
          } else {
            variable.dataIndexExpr.push({ dIdx: column.dataIndex, expr: "" });
          }
          if ((_a2 = column.aggregates) == null ? void 0 : _a2.some((a) => (a.type || a) === "totalSummary")) {
            variable.summaryCols.push(column.dataIndex);
          }
        }
        column.idx = column.idx ?? index;
        if (column.hidden) {
          column.propColumnIndex = index;
          column.dataIndex && (this.dataIndexMap[column.dataIndex] = { ...column });
          return;
        }
        if (!column.dataIndex) {
          column.dataIndex = column.stateId || `${this.uniqueId}_${index}`;
        }
        let textAlign = column.align || align;
        if (["amount", "amt", "qty", "prc", "rate", "percent", "number"].includes((_b = column.editor) == null ? void 0 : _b.type) || ["InputNumber", "inputnumber"].includes((_c = column.editor) == null ? void 0 : _c.xtype)) {
          const defaultCfg = {
            amount: {
              prefix: "￥",
              nullValue: "--"
            },
            percent: {
              suffix: "%"
            },
            rate: {
              suffix: "%",
              formatter({ value, precision }) {
                const p = precision ? Math.max(0, precision - 2) : void 0;
                const f = import_util.util.numberPrecision(value * 100, p);
                if (p !== void 0 && f) {
                  return f.toFixed(p);
                }
                return f;
              }
            }
          };
          textAlign = column.align || "right";
          column.format = {
            type: "number",
            precision: (0, import_util.getGlobalConfig)().default.precision[column.editor.type] ?? column.editor.precision,
            ...defaultCfg[column.editor.type],
            ...column.format
          };
        }
        if (textAlign) {
          column.headerStyle = { textAlign, ...column.headerStyle };
          column.cellStyle = { textAlign, ...column.cellStyle };
        }
        if (!import_util.util.isFunction(column.render) && (column.format || column.render) || column.encrypted) {
          column.render = (0, import_util.getRender)(column);
        }
        expandDataIndex = expandDataIndex || column.dataIndex;
        if (column.hasOwnProperty("oldRender")) {
          column.render = column.oldRender;
          delete column.oldRender;
        }
        if (expandDataIndex === column.dataIndex) {
          if (isTree || expandRow && expandCfgDataIndex) {
            this.expandColumn = column;
            column.oldRender = column.render;
            fixed !== void 0 && (column.fixed = fixed);
            if (textAlign === "left") {
              column.headerStyle = {
                ...column.headerStyle,
                paddingLeft: expandIconWidth
              };
            }
          }
          if (isTree) {
            column.render = (...args) => {
              const { dataIndex, rowIndex, table } = args[0];
              const row = this.getRow(rowIndex);
              const children = column.oldRender ? column.oldRender(...args) : (0, import_util.displayText)(row[dataIndex]);
              const level = row[TREE_LEVEL] || 1;
              const isLastChild = row[TREE_LAST_CHILD] || rowIndex === table.getRows().length - 1;
              const hasIcon = row.children && row.children.length > 0;
              return /* @__PURE__ */ import_react.default.createElement(
                "span",
                {
                  className: `level-${level}${isLastChild ? " tree-last-child" : ""}${showLine ? " show-line" : ""}${block ? "" : " tree-unblock"}`,
                  style: {
                    display: "flex",
                    alignItems: "center",
                    height: "100%",
                    minWidth: "100%",
                    whiteSpace: "nowrap",
                    flexWrap: "nowrap",
                    marginLeft: 0 - cellPadding
                  }
                },
                new Array(level - 1).fill(1).map((v, i) => {
                  return /* @__PURE__ */ import_react.default.createElement("span", { key: i, className: `empty-zw`, style: { width: expandIconWidth } });
                }),
                hasIcon ? /* @__PURE__ */ import_react.default.createElement(
                  import_expand.ExpandIcon,
                  {
                    key: "icon",
                    rowIndex,
                    row,
                    table: tableIns,
                    icon: icon || ((expanded) => /* @__PURE__ */ import_react.default.createElement(
                      "span",
                      {
                        className: `iup-row-expand-icon ${expanded ? "iup-row-expand-icon-expanded" : "iup-row-expand-icon-collapsed"}`,
                        style: { zIndex: 1, width: `${compact ? 12 : 16}px`, height: `${compact ? 12 : 16}px` }
                      }
                    )),
                    style: { width: expandIconWidth }
                  }
                ) : /* @__PURE__ */ import_react.default.createElement("span", { key: "leaf-line", className: `empty-zw leaf-node`, style: { width: expandIconWidth } }),
                /* @__PURE__ */ import_react.default.createElement("span", { style: { flex: 1, textAlign } }, children)
              );
            };
            column.cellStyle = {
              ...column.cellStyle,
              textAlign: "left"
            };
          } else if (expandRow && expandCfgDataIndex) {
            column.render = (...args) => {
              const { dataIndex, rowIndex } = args[0];
              const row = this.getRow(rowIndex);
              const children = column.oldRender ? column.oldRender(...args) : (0, import_util.displayText)(row[dataIndex]);
              return /* @__PURE__ */ import_react.default.createElement(
                "span",
                {
                  style: {
                    display: "flex",
                    alignItems: "center",
                    height: "100%",
                    minWidth: "100%",
                    whiteSpace: "nowrap",
                    flexWrap: "nowrap",
                    justifyContent: textAlign,
                    marginLeft: 0 - cellPadding
                  }
                },
                expandIconWidth > 0 ? /* @__PURE__ */ import_react.default.createElement(
                  import_expand.ExpandIcon,
                  {
                    key: "icon",
                    rowIndex,
                    row,
                    table: tableIns,
                    icon: icon || ((expanded) => /* @__PURE__ */ import_react.default.createElement(
                      "span",
                      {
                        className: `ant-table-row-expand-icon ${expanded ? "ant-table-row-expand-icon-expanded" : "ant-table-row-expand-icon-collapsed"}`,
                        style: { zIndex: 1, transform: `scale(${compact ? 0.65 : 0.8})` }
                      }
                    )),
                    style: { width: expandIconWidth }
                  }
                ) : null,
                children
              );
            };
          }
          delete column.columnSort;
        }
        if (isTree || column.editor) {
          delete column.mergeCell;
        }
        if (isTree) {
          delete column.sortable;
        }
        if (column.aggregates && column.aggregates.length > variable.aggregates.length) {
          variable.aggregates = column.aggregates;
        }
        if (!column.width && !column.flex) {
          column.flex = 1;
        }
        if (column.offsetWidth) {
          delete column.flex;
          column.width = column.offsetWidth;
        }
        if (!column.flex && column.width) {
          variable.usedWidth += column.width;
          variable.totalColumnWidth += column.width;
        }
        let newColumn;
        if (column.groupIn) {
          if (import_util.util.isString(column.groupIn)) {
            column.groupIn = [column.groupIn];
          }
          if (column.groupIn.length > 0) {
            variable.headerLine = Math.max(variable.headerLine, column.groupIn.length + (column.title ? 1 : 0));
            variable.groupable = true;
            delete column.columnSort;
          } else {
            delete column.groupIn;
          }
        }
        if (!column.dataIndex) {
          import_util.util.debug({ msg: `column dataIndex is empty, auto generate dataIndex_${index}`, type: "warn" });
          column.dataIndex = `dataIndex_${index}`;
          delete column.sortable;
        }
        column.propColumnIndex = index;
        if (column.fixed) {
          delete column.mergeCell;
          delete column.columnSort;
          if (column.fixed === "right") {
            newColumn = {
              ...column,
              columnIndex: columnIndex.right++
            };
            rightFixedColumns.push(newColumn);
          } else {
            newColumn = {
              ...column,
              columnIndex: columnIndex.left++
            };
            leftFixedColumns.push(newColumn);
          }
        } else {
          newColumn = {
            ...column,
            columnIndex: columnIndex.normal++
          };
          if (column.columnSort) {
            variable.columnSort = column.columnSort;
          }
          normalColumns.push(newColumn);
        }
        if (newColumn.editor) {
          newColumn.originEditor = newColumn.editor;
          const xType = import_util.util.isString(column.editor.xtype) ? column.editor.xtype.toLowerCase() : "";
          if (this.showEditor.includes(xType)) {
            if (xType === "attachment") {
              newColumn.render = (0, import_util.getRender)({
                ...newColumn,
                editor: {
                  regExp: {
                    exp({ row, dataIndex }) {
                      const { required, min: minLen, max, maxLength, nameField } = newColumn.originEditor || {};
                      const maxLen = max ?? maxLength;
                      const displayField = nameField || `${dataIndex}FileCount`;
                      const len = row[displayField] ?? 0;
                      if (import_util.util.isNumber(maxLen) && len > maxLen) {
                        return `附件最大数量不能大于${maxLen}`;
                      }
                      if (import_util.util.isNumber(minLen) && len < minLen) {
                        return `附件最小数量不能小于${minLen}`;
                      }
                      if (required && len === 0) {
                        return "必须上传附件";
                      }
                      return true;
                    },
                    info: "必须上传附件"
                  },
                  ...newColumn.originEditor,
                  listeners: {
                    onBeforeInit: ({ row, dataIndex }) => {
                      if (this.isDisabled({ row, dataIndex, column })) {
                        return false;
                      }
                      return true;
                    },
                    onChange: async (result, { table, row, dataIndex, displayField, rowIndex, lastRow }) => {
                      var _a3, _b2, _c2, _d;
                      row[dataIndex] = result.asrSessionGuid;
                      row[displayField] = ((_a3 = result.attachmentRecordList) == null ? void 0 : _a3.length) || 0;
                      await ((_d = (_c2 = (_b2 = newColumn.originEditor) == null ? void 0 : _b2.listeners) == null ? void 0 : _c2.onChange) == null ? void 0 : _d.call(_c2, {
                        value: result.asrSessionGuid,
                        row,
                        lastRow,
                        rowIndex,
                        table,
                        dataIndex,
                        getEditor: () => null,
                        originValue: result
                      }));
                      table.updateRow(row);
                    }
                  }
                },
                format: { type: "attachment", oType: import_util.util.getQueryValue("oType") }
              });
            } else {
              const checkedAll = column.editor.checkedAll ?? true;
              if (xType === "checkbox" && column.editor.checkStrictly === false) {
                if (column.header && !checkedAll) {
                  column.headerStyle = { ...column.headerStyle, ...(0, import_util.convertStyle)({ textAlign: "center" }) };
                } else {
                  newColumn.header = () => /* @__PURE__ */ import_react.default.createElement(
                    import_check.AllCheckBox,
                    {
                      table: tableIns,
                      dataIndex: column.dataIndex,
                      checkDisabled: column.editor.disabled,
                      children: column.header
                    }
                  );
                }
              }
              newColumn.render = ({ table, rowIndex, dataIndex }) => {
                const row = this.getRow(rowIndex);
                if (xType === "checkbox" && column.editor.checkStrictly === false) {
                  return /* @__PURE__ */ import_react.default.createElement(
                    import_check.RowCheckBox,
                    {
                      table: tableIns,
                      dataIndex,
                      row,
                      rowIndex,
                      checkDisabled: column.editor.disabled
                    }
                  );
                }
                const style = column.align ? (0, import_util.convertStyle)({ textAlign: column.align }) : {};
                return /* @__PURE__ */ import_react.default.createElement(
                  import_factory.EditorFactory,
                  {
                    column: { ...column },
                    style,
                    row,
                    table,
                    editing: true,
                    rendered: true
                  }
                );
              };
            }
            delete newColumn.editor;
          } else {
            editableColumnIndex.push(index);
          }
        }
        if (newColumn.flex) {
          variable.totalFlex += newColumn.flex;
          unsetWidthColumns.push(newColumn);
        }
        if (this.dataIndexMap.hasOwnProperty(column.dataIndex)) {
          import_util.util.debug({ msg: `column dataIndex is duplicate, delete from column ${index}`, type: "warn" });
        } else {
          column.columnIndex = newColumn.columnIndex;
          this.dataIndexMap[column.dataIndex] = { ...column };
        }
      });
      if (variable.totalFlex === 0) {
        const flexColumn = normalColumns[normalColumns.length - 1];
        if (flexColumn) {
          flexColumn.flex = 1;
          flexColumn.resizable = false;
          variable.totalFlex = 1;
          variable.usedWidth -= flexColumn.width;
          variable.totalColumnWidth -= flexColumn.width;
          unsetWidthColumns.push(flexColumn);
        }
      }
      const columnDefaultWidth = 80;
      let unUsedWidth = offsetWidth - variable.usedWidth - unsetWidthColumns.reduce((p, c) => p + (c.width ?? columnDefaultWidth), 0);
      const flexWidth = Math.ceil(unUsedWidth / variable.totalFlex);
      unsetWidthColumns.forEach((column, idx) => {
        const defaultColumn = this.dataIndexMap[column.dataIndex];
        const minWidth = column.width ?? columnDefaultWidth;
        if (flexWidth <= 0) {
          column.width = minWidth;
        } else if (idx < unsetWidthColumns.length - 1) {
          column.width = minWidth + column.flex * flexWidth;
          unUsedWidth -= column.flex * flexWidth;
        } else {
          column.width = minWidth + unUsedWidth;
        }
        if (this.expandColumn && this.expandColumn.dataIndex === column.dataIndex) {
          this.expandColumn.offsetWidth = column.width;
        }
        column.offsetWidth = column.width;
        variable.totalColumnWidth += column.width;
        if (defaultColumn) {
          defaultColumn.width = column.width;
          defaultColumn.offsetWidth = column.width;
        }
      });
      let [leftW, rightW] = [
        leftFixedColumns.reduce((w, c) => w + c.width, 0),
        rightFixedColumns.reduce((w, c) => w + c.width, 0)
      ];
      if (leftW + rightW > offsetWidth) {
        if (leftW > offsetWidth) {
          [].unshift.apply(normalColumns, leftFixedColumns);
          leftW = 0;
          leftFixedColumns.length = 0;
        }
        [].push.apply(normalColumns, rightFixedColumns);
        rightW = 0;
        rightFixedColumns.length = 0;
      }
      this.cacheColumns = {
        headerLineHeight: this.props.headerHeight || 39,
        groupable: variable.groupable,
        columnSort: variable.columnSort,
        dataIndexExpr: variable.dataIndexExpr,
        editableColumnIndex,
        totalColumnWidth: variable.totalColumnWidth,
        avgColumnWidth: Math.floor(variable.totalColumnWidth / Math.max(1, normalColumns.length)),
        // 平均列宽
        aggregates: variable.aggregates,
        normalColumns: this.getGroupColumns(normalColumns, "normal"),
        fixedColumns: {
          left: {
            columns: this.getGroupColumns(leftFixedColumns, "left"),
            width: leftW
          },
          right: {
            columns: this.getGroupColumns(rightFixedColumns, "right"),
            width: rightW
          }
        },
        unUsedWidth: unsetWidthColumns.length > 0 ? 0 : Math.max(0, offsetWidth - variable.usedWidth),
        useFlex: offsetWidth >= variable.totalColumnWidth,
        allColumns,
        summaryCols: variable.summaryCols
      };
      this.headerHeight = this.cacheColumns.headerLineHeight * variable.headerLine + 1;
      (_a = this.outRef.current) == null ? void 0 : _a.resetAfterColumnIndex(0, false);
    }
    return this.cacheColumns;
  }
  /**
   * 生成ds
   * @param ds
   * @param expandTree
   */
  generateDataSource(ds, expandTree = void 0) {
    const { groupBy, expandCfg, isTree, expandRow } = this.props;
    const defaultExpand = (expandCfg == null ? void 0 : expandCfg.defaultExpand) ?? this.props.defaultExpand;
    const { columns } = this.state;
    const newDs = this.props.aggregatePosition === "start" && this.generateColumns().aggregates.length > 0 ? [
      {
        cellType: import_common.CellTypeEnum.AggregateCell,
        parent: null,
        groupIndex: -1
      }
    ] : [];
    const expandField = this.getExpandField();
    const keyField = this.getKeyField();
    if (expandRow) {
      let idx = 1;
      this.groupDs = [];
      ds.forEach((r, index) => {
        let expand = r[expandField];
        if (expand === void 0) {
          if (r[keyField] && this._expandedKeys.has(r[keyField])) {
            expand = true;
            r[expandField] = expand;
          } else if (defaultExpand) {
            expand = import_util.util.isFunction(defaultExpand) ? defaultExpand({
              row: r,
              index
            }) : defaultExpand === "all" || index === 0;
            r[expandField] = expand;
          }
        }
        r["__index__"] = idx++;
        this._setExpandedKeys(r, idx);
        this.groupDs.push(r);
        newDs.push(r);
        if (expand) {
          newDs.push({
            cellType: import_common.CellTypeEnum.ExpandRowCell,
            parent: r,
            groupIndex: index
          });
        }
      });
      return newDs;
    } else if (groupBy && columns) {
      const lastGroupDs = this.groupDs;
      const groupArr = import_util.util.groupBy(ds, (data) => data[groupBy]);
      if (!this.groupByColumn) {
        this.groupByColumn = columns.find(({ dataIndex }) => dataIndex === groupBy);
      }
      let idx = 1;
      this.groupDs = [];
      groupArr.forEach((group, index) => {
        var _a;
        let expand = this._expandedKeys.has(group.groupKey) || ((_a = lastGroupDs.find((g) => g[groupBy] === group.groupKey)) == null ? void 0 : _a[expandField]);
        if (expand === void 0 && defaultExpand) {
          expand = import_util.util.isFunction(defaultExpand) ? defaultExpand({
            row: group,
            index
          }) : defaultExpand === "all" || index === 0;
        }
        const dr = {
          [import_common.IS_GROUP]: true,
          column: this.groupByColumn,
          [groupBy]: group.groupKey,
          children: group.children,
          [expandField]: expand
        };
        this._setExpandedKeys(dr, index);
        this.groupDs.push(dr);
        group.children.forEach((r) => {
          r["__index__"] = idx++;
          r[GROUP_PARENT] = dr;
        });
        this._generateGroupDs(newDs, dr, index);
      });
      return newDs;
    } else if (isTree && (expandTree || defaultExpand)) {
      const paramLevel = Number((expandTree == null ? void 0 : expandTree.level) ?? -1);
      const strictly = expandTree == null ? void 0 : expandTree.strictly;
      this.expandLevel = 0;
      const isExpand = (param) => {
        if (!param.row.children || param.row.children.length === 0) {
          return false;
        }
        if (paramLevel > -1) {
          return param.level <= paramLevel;
        }
        if (param.row[keyField] && this._expandedKeys.has(param.row[keyField])) {
          return true;
        }
        if (import_util.util.isFunction(defaultExpand)) {
          return defaultExpand(param);
        }
        return param.level <= (defaultExpand === "all" ? 99 : Number(defaultExpand));
      };
      const loop = (dataRows, parentRow, level, todo) => {
        if (!dataRows)
          return;
        const len = dataRows.length - 1;
        dataRows.forEach((r, index) => {
          const children = r.children;
          updateTreeSymbol({ parentNode: parentRow, node: r, index, level, isLeaf: !(children == null ? void 0 : children.length) });
          r[TREE_LAST_CHILD] = index === len;
          if (todo == null ? void 0 : todo(r, index, level)) {
            loop(children, r, level + 1, todo);
          } else {
            r[expandField] = false;
            loop(children, r, level + 1);
          }
        });
      };
      const createDs = (dataRows, parentRow, firstLevel) => {
        loop(dataRows, parentRow, firstLevel, (r, index, level) => {
          this.expandLevel = Math.max(this.expandLevel, level);
          if (strictly || !r[expandField]) {
            r[expandField] = isExpand({ row: r, index, level });
          }
          this._setExpandedKeys(r, index + "" + level);
          newDs.push(r);
          return r[expandField];
        });
      };
      createDs(ds, void 0, 1);
      return newDs;
    }
    if (this.props.aggregatePosition === "start") {
      return this.generateColumns().aggregates.length > 0 ? [
        {
          cellType: import_common.CellTypeEnum.AggregateCell,
          parent: null,
          groupIndex: -1
        },
        ...ds
      ] : ds;
    }
    return ds;
  }
  setEditLock(lock) {
    this._lockEdit = lock;
  }
  componentDidMount() {
    this.subscribe((keyCode) => {
      var _a, _b;
      (_b = (_a = this.props).onKeyDown) == null ? void 0 : _b.call(_a, { keyCode });
    }, "keyboardEvent");
    this.subscribe(() => {
      var _a;
      if (!this.rootEl) {
        this.rootEl = document.body;
        (_a = this.rootEl) == null ? void 0 : _a.addEventListener("click", this._onRootElementClick, false);
      }
    }, "startEditing");
  }
  componentWillUnmount() {
    var _a;
    if (this._isCacheKey("selected")) {
      import_util.util.setCache(
        `${this.uniqueId}_selected`,
        {
          selected: this.getSelectedIndexes(),
          highlight: this.getSelectedIndex()
        },
        { type: "session" }
      );
    }
    if (this._isCacheKey("page") && this.props.pagination) {
      const { pageIndex, pageSize } = this.state.params;
      import_util.util.setCache(`${this.uniqueId}_page`, { pageIndex, pageSize }, { type: "session" });
    }
    this.unmount = true;
    this._observer.clear();
    this._expandedKeys.clear();
    this.resetSelected();
    (_a = this.rootEl) == null ? void 0 : _a.removeEventListener("click", this._onRootElementClick, false);
    this.rootEl = null;
  }
  componentDidUpdate() {
    var _a, _b;
    this.lastUpdateFlag = this.updateFlag;
    this.updateFlag = import_common.UpdateFlagEnum.None;
    if (this.expandLevel) {
      const { isTree, expandCfg = {} } = this.props;
      if (isTree && expandCfg.fitContent !== false) {
        const expandColumn = this.expandColumn || {};
        const initWidth = expandColumn.offsetWidth || expandColumn.width;
        let maxWidth = 0;
        (_a = this.bodyRef.current) == null ? void 0 : _a.querySelectorAll(`.level-${this.expandLevel}`).forEach((el) => {
          maxWidth = Math.max(el.scrollWidth + this._getCellPadding() * 2, maxWidth);
        });
        maxWidth > 0 && (this.expandLevel = 0);
        if (maxWidth > initWidth) {
          this.setColumnProps((_b = this.expandColumn) == null ? void 0 : _b.dataIndex, { offsetWidth: maxWidth });
        }
      }
    }
  }
  updateStateByProps() {
    var _a;
    if (this.state.changedFields.length > 0) {
      if (this.state.changedFields.indexOf("dataSource") > -1) {
        const ds = this.props.dataSource;
        if (this.store.raw === this._defaultDs && ds) {
          this.store.raw = this.deepCopyRaw(ds);
        }
        this.resetSelected(ds);
        this.store.aggregateData = ds || [];
        this.store.data = ds || [];
        this.state.dataSource = this.generateDataSource(this.store.data, {});
        this.updateFlag = import_common.UpdateFlagEnum.ForceUpdate;
        this._resetRowHeight({ immediate: false });
      }
      if (this.state.changedFields.indexOf("columns") > -1) {
        this.cacheColumns = null;
        this.state.columns = this._loadColumnState(this.props.columns, true);
      }
      this.state.changedFields = [];
    } else if (((_a = this._lastProps) == null ? void 0 : _a.dataIndexProps) !== this.props.dataIndexProps) {
      this.cacheColumns = null;
      this.state.columns = this._loadColumnState(this.state.columns);
    }
    this.cellStyle = { padding: `0 ${this._getCellPadding()}px` };
  }
  shouldComponentUpdate(nextProps, nextState) {
    const compareProps = ["checkbox", "showRowNumber", "dataIndexProps"];
    const compareStates = ["width", "columns", "updateTime"];
    if (compareStates.some((prop) => this.state[prop] !== nextState[prop]) || compareProps.some((prop) => this.props[prop] !== nextProps[prop])) {
      this.cacheColumns = null;
    }
    if (["disabled", "dataIndexProps"].some((prop) => this.props[prop] !== nextProps[prop])) {
      this.updateFlag = import_common.UpdateFlagEnum.ForceUpdate;
    }
    this._lastProps = this.props;
    return true;
  }
  async _queryPromise(params = {}) {
    var _a;
    const { request, response, pagination, fullyControlled, queryResetIndex } = this.props;
    if (fullyControlled) {
      return;
    }
    if (this._isPagination) {
      this._isPagination = false;
    } else {
      this._requestPaginationData = null;
      queryResetIndex && (params.pageIndex = 1);
    }
    if (request) {
      if (!this._requestPaginationData) {
        this.startLoading();
        const newParams = ((_a = this.cacheColumns.summaryCols) == null ? void 0 : _a.length) ? { ...params, summaryCols: this.cacheColumns.summaryCols.join() } : params;
        const res = import_util.util.parseJson(await request(newParams, this)) || [];
        const result = response ? response(res) : res;
        if (pagination && import_util.util.isArray(result)) {
          this._requestPaginationData = result;
        } else {
          this._requestPaginationData = null;
          return result;
        }
      }
      if (this._requestPaginationData) {
        return {
          total: this._requestPaginationData.length,
          record: this._requestPaginationData.slice(
            (params.pageIndex - 1) * params.pageSize,
            params.pageIndex * params.pageSize
          )
        };
      }
    }
    return [...this.store.data];
  }
  /**
   * 设置loading状态
   */
  startLoading() {
    if (!this.state.loading) {
      this.setState({ loading: true });
    }
  }
  /**
   * 取消loading状态
   */
  endLoading() {
    if (this.state.loading) {
      this.setState({ loading: false });
    }
  }
  /**
   * 获取单元格的错误信息
   * @param row 行
   * @param dataIndex 列字段
   * @param errors 错误信息
   */
  _cellError(row, dataIndex, errors) {
    var _a;
    errors = errors || this.state.errors;
    if (row && dataIndex) {
      const keyValue = row[this.getKeyField()];
      const columns = this.cacheColumns.allColumns || this.state.columns;
      const column = columns.find((c) => c.dataIndex === dataIndex);
      if (column && column.editor && row) {
        const value = row[column.dataIndex];
        const { required = false, regExp, min, max, maxLength } = column.editor;
        const errorArr = [];
        if (regExp) {
          const exp = regExp.exp || regExp;
          const info = regExp.info || "数据格式错误";
          const result = import_util.util.regExpTest(exp, import_util.util.isFunction(exp) ? { row, value, dataIndex } : value);
          if (result !== true) {
            errorArr.push(["regExp", import_util.util.isString(result) ? result || info : info]);
          }
        } else if (import_util.util.isNullOrEmpty(value) || import_util.util.isArray(value) && value.length === 0) {
          if (required) {
            errorArr.push(["required", "必输项"]);
          }
        } else {
          if (import_util.util.isNumber(maxLength) && import_util.util.strLen(value) > maxLength) {
            errorArr.push(["maxLength", `最大长度不能超过${maxLength}`]);
          }
          if (import_util.util.isNumber(min) && value < min) {
            errorArr.push(["min", `最小值不能小于${min}`]);
          }
          if (import_util.util.isNumber(max) && value > max) {
            errorArr.push(["max", `最大值不能大于${max}`]);
          }
        }
        if (errorArr.length > 0) {
          errors[`${keyValue}:${dataIndex}`] = {
            title: (_a = this.getDataIndexMap()[dataIndex]) == null ? void 0 : _a.title,
            rowIndex: this.getRowIndex(row),
            dataIndex,
            info: errorArr
          };
        } else {
          delete errors[`${keyValue}:${dataIndex}`];
        }
      }
    }
    return errors;
  }
  /**
   * 获取错误信息
   */
  getErrors() {
    return new Promise((resolve) => {
      this.validData(() => {
        resolve(this.state.errors);
      });
    });
  }
  /**
   * 数据验证
   */
  validData(callback) {
    const { dataSource } = this.state;
    const validRow = (row) => {
      const errors2 = {};
      const columns = this.cacheColumns.allColumns || this.state.columns;
      columns.forEach((c) => {
        this._cellError(row, c.dataIndex, errors2);
      });
      return errors2;
    };
    const errors = dataSource.reduce((p, r) => ({ ...p, ...validRow(r) }), {});
    const errorKey = Object.keys(errors).find((key) => errors[key].info.length > 0);
    if (errorKey) {
      const { rowIndex, dataIndex } = errors[errorKey];
      const { selected } = this.state;
      this.scrollToItem({ rowIndex, dataIndex, align: "smart" });
      this.refreshView({
        callback,
        state: selected.editing && selected.rowIndex > -1 && selected.dataIndex ? { selected: { ...selected, editing: false }, errors } : { errors }
      });
    } else if (Object.keys(this.state.errors || {}).length) {
      this.refreshView({
        callback,
        state: { errors }
      });
    } else {
      callback == null ? void 0 : callback();
    }
    return !errorKey;
  }
  isValid() {
    return new Promise((resolve) => {
      this.validData(() => {
        resolve(!Object.keys(this.state.errors || {}).length);
      });
    });
  }
  getActiveEditor() {
    var _a;
    return (_a = this._activeEditor) == null ? void 0 : _a.getApi();
  }
  isDisabled({ row, dataIndex, column }) {
    var _a;
    if (!column && dataIndex) {
      column = this.getDataIndexMap()[dataIndex];
    }
    if (!dataIndex && column) {
      dataIndex = column.dataIndex;
    }
    if (this.props.readOnly) {
      if (import_util.util.isFunction(this.props.readOnly)) {
        return this.props.readOnly({ row, dataIndex });
      }
      return true;
    }
    if (((_a = column == null ? void 0 : column.editor) == null ? void 0 : _a.disabled) !== void 0) {
      return import_util.util.isFunction(column.editor.disabled) ? column.editor.disabled({
        row,
        dataIndex
      }) : column.editor.disabled;
    }
    if (this.props.disabled) {
      if (import_util.util.isFunction(this.props.disabled)) {
        return this.props.disabled({ row, dataIndex });
      }
      return true;
    }
    if ((column == null ? void 0 : column.levelSummary) && this.props.isTree) {
      return row[TREE_LEAF_NODE] === false;
    }
    return false;
  }
  /**
   * 设置单元格编辑状态
   * @param rowIndex 行号
   * @param dataIndex 列字段
   */
  startEditing({ rowIndex, dataIndex = void 0 }, payload = {}) {
    if (this.isDisabled({ row: this.getRow(rowIndex), dataIndex })) {
      return;
    }
    const { selected } = this.state;
    const { allColumns, editableColumnIndex } = this.generateColumns();
    if (editableColumnIndex.length === 0)
      return;
    dataIndex = dataIndex || allColumns[editableColumnIndex[0]].dataIndex;
    if (!selected.editing || selected.rowIndex !== rowIndex || selected.dataIndex !== dataIndex) {
      this.scrollToItem({ rowIndex, dataIndex, align: "smart" });
      this.setState(
        {
          selected: {
            rowIndex,
            dataIndex,
            editing: true
          },
          errors: this._cellError(this.getRow(selected.rowIndex), selected.dataIndex)
        },
        () => {
          if (selected.editing) {
            this.notify({ ...selected, payload }, "endEditing");
          }
          this.notify({ ...this.state.selected, payload }, "startEditing");
        }
      );
      return true;
    }
    return false;
  }
  focus() {
    var _a, _b;
    const { selected } = this.state;
    if (!this.startEditing({
      rowIndex: Math.max(selected.rowIndex, 0),
      dataIndex: selected.dataIndex
    })) {
      (_b = (_a = this.getActiveEditor()) == null ? void 0 : _a.focus) == null ? void 0 : _b.call(_a);
    }
  }
  /**
   * 取消单元格编辑状态
   */
  endEditing(sync = false, focused = true) {
    var _a, _b;
    const { selected } = this.state;
    const execFn = sync ? (handler) => handler() : setTimeout;
    focused && ((_b = (_a = this.bodyRef.current) == null ? void 0 : _a.focus) == null ? void 0 : _b.call(_a));
    if (selected.editing && selected.rowIndex > -1 && selected.dataIndex) {
      execFn(() => {
        this.setState(
          {
            selected: {
              ...selected,
              rowIndex: -1,
              editing: false
            },
            errors: this._cellError(this.getRow(selected.rowIndex), selected.dataIndex)
          },
          () => {
            this.notify(selected, "endEditing");
            this._activeEditor = null;
            this.setEditLock(false);
          }
        );
      }, 5);
      return true;
    }
    return false;
  }
  /**
   * 按列排序数据
   * @param orderBy 数组，排序方式，例如：[{field1: 'asc'}, {field2:'desc'}]
   */
  setOrderBy(orderBy, callback) {
    const orderData = this.generateDataSource((0, import_util.dataSortOrder)(this.store.data, orderBy, this.getDataIndexMap()));
    this.refreshView({
      state: { orderBy, dataSource: orderData },
      rowColumnIndex: { rowIndex: 0 },
      callback
    });
  }
  /**
   * 获取当前索引对应的数据
   * @param rowIndex 行索引
   */
  getRow(rowIndex) {
    if (rowIndex < 0) {
      return null;
    }
    const keyField = this.getKeyField();
    const rowData = this._renderDataSource ? this._renderDataSource[rowIndex] : this.getRows()[rowIndex];
    if (rowData && rowData[keyField] === void 0) {
      rowData[keyField] = import_util.util.uniqueId(rowIndex) + "_$_";
      this._setKeyMap(rowData);
    }
    return rowData;
  }
  /**
   * 获取主键对应的数据
   * @param keyValue 主键value值
   */
  getRowByKey(keyValue) {
    if (import_util.util.isNullOrEmpty(keyValue)) {
      return null;
    }
    let find = this._keyMap.get(keyValue);
    if (!find) {
      const keyField = this.getKeyField();
      const loop = (rows) => {
        if (!rows) {
          return false;
        }
        for (let i = 0, len = rows.length; i < len; i++) {
          if (rows[i][keyField] === keyValue) {
            find = rows[i];
            this._setKeyMap(find);
            return true;
          }
          if (loop(rows[i].children)) {
            return true;
          }
        }
        return false;
      };
      loop(this.getStore().data);
    }
    return find;
  }
  /**
   * 获取所有行数据（按照真实显示返回）
   */
  getRows() {
    return this.state.dataSource || [];
  }
  getRenderRows() {
    return this._renderDataSource || this.getRows();
  }
  /**
   * 复制行数据
   * @param row 行索引或者行数据
   * @param except 需要排除的字段
   */
  copyRow(row, except = ["checked"]) {
    this._copyRow = import_util.util.deepCopy(import_util.util.isNumber(row) ? this.getRow(row) : row, true);
    except.forEach((field) => {
      delete this._copyRow[field];
    });
    delete this._copyRow[this.getKeyField()];
    return this._copyRow;
  }
  /**
   * 粘贴行数据
   */
  pasteRow(rowIndex) {
    if (!this._copyRow) {
      return false;
    }
    if (rowIndex === void 0) {
      rowIndex = this.getSelectedIndex();
    }
    if (rowIndex > -1) {
      this.updateRowDataByIndex(rowIndex, this._copyRow, false);
      return true;
    }
    return false;
  }
  /**
   * 剪切行数据
   */
  cutRow(rowIndex) {
    if (rowIndex === void 0) {
      rowIndex = this.getSelectedIndex();
    }
    if (rowIndex > -1) {
      this.copyRow(rowIndex);
      this.clearData(rowIndex);
      return true;
    }
    return false;
  }
  /**
   * 获取行索引
   * @param row 数据行
   */
  getRowIndex(row) {
    if (import_util.util.isFunction(row)) {
      return this.getRows().findIndex(row);
    }
    return this.getRows().indexOf(row);
  }
  /**
   * 获取所有数据
   */
  getStore() {
    return {
      raw: this.rawData,
      data: this.store.data
    };
  }
  getData() {
    return this.store.data;
  }
  watchPromise() {
    return this.store.raw;
  }
  getAggregateData() {
    return this.updateFlag > 1 ? [...this.store.aggregateData] : this.store.aggregateData;
  }
  // size变化时是否重置grid的缓存样式
  shouldResetStyleCacheOnItemSizeChange() {
    return this.props.expandRow || this.props.isTree || this.groupByColumn;
  }
  /**
   * 设置行的展开状态
   * @param rowIndexes
   * @param expandInfo
   */
  setExpand(rowIndexes = void 0, expandInfo = true) {
    var _a;
    if (!this.shouldResetStyleCacheOnItemSizeChange()) {
      this.refreshView({ endEditing: true });
      (_a = expandInfo == null ? void 0 : expandInfo.callback) == null ? void 0 : _a.call(expandInfo);
      return;
    }
    const ds = this.getRows();
    const isLevelExpand = expandInfo.hasOwnProperty("level");
    const maxLevel = isLevelExpand ? expandInfo.level : expandInfo ? 99 : -1;
    this.expandLevel = 0;
    this.endEditing(true);
    let rowIndexArr = Array.isArray(rowIndexes) ? rowIndexes : import_util.util.isNumber(rowIndexes) ? [rowIndexes] : [];
    let currentMinRowIndex;
    if (rowIndexes === -1) {
      currentMinRowIndex = 0;
      rowIndexArr = [];
    } else if (rowIndexArr.length === 0) {
      rowIndexArr = ds.map((d, idx) => idx);
    } else {
      currentMinRowIndex = Math.min(...rowIndexArr);
    }
    const expandField = this.getExpandField();
    rowIndexArr.forEach((index) => {
      const row = ds[index];
      const rowLevel = row[TREE_LEVEL] ?? 1;
      row[expandField] = rowLevel <= maxLevel;
      this._setExpandedKeys(row, index);
      row.__update__ = { rowIndex: index, dataIndex: expandField };
      if (isLevelExpand && row[expandField] && rowLevel < maxLevel) {
        import_util.util.loopChildren(
          row,
          (r, i, level) => {
            if (level < maxLevel) {
              r[expandField] = true;
              this._setExpandedKeys(row, i + "" + level);
            } else {
              return false;
            }
          },
          rowLevel
        );
      }
    });
    const newState = {};
    if (this.props.isTree) {
      newState.dataSource = [];
      const createDs = (dataRows, parentRow, level) => {
        this.expandLevel = Math.max(this.expandLevel, level);
        const len = dataRows.length - 1;
        dataRows.forEach((r, index) => {
          const children = r.children;
          const lastChild = index === len;
          updateTreeSymbol({ parentNode: parentRow, node: r, index, level, isLeaf: !(children == null ? void 0 : children.length) });
          if (r[TREE_LAST_CHILD] !== lastChild) {
            r[TREE_LAST_CHILD] = lastChild;
            r.__update__ = {};
          }
          newState.dataSource.push(r);
          if (r[expandField] && children) {
            createDs(children, r, level + 1);
          }
        });
      };
      createDs(this.store.aggregateData, void 0, 1);
    } else if (this.groupByColumn) {
      newState.dataSource = [];
      this.groupDs.forEach((g, index) => {
        this._generateGroupDs(newState.dataSource, g, index);
      });
    } else if (this.props.expandRow) {
      newState.dataSource = [];
      this.groupDs.forEach((r, index) => {
        newState.dataSource.push(r);
        if (r[expandField]) {
          newState.dataSource.push({ groupIndex: index, parent: r, cellType: import_common.CellTypeEnum.ExpandRowCell });
        }
      });
    }
    this._resetRowHeight({ immediate: false, rowIndex: currentMinRowIndex });
    if (newState.dataSource && this.props.aggregatePosition === "start" && this.generateColumns().aggregates.length > 0) {
      newState.dataSource.unshift({
        cellType: import_common.CellTypeEnum.AggregateCell,
        parent: null,
        groupIndex: -1
      });
    }
    this.setState(
      {
        ...newState,
        currentExpandRow: {
          rowIndex: rowIndexArr,
          expanded: expandInfo
        }
      },
      expandInfo == null ? void 0 : expandInfo.callback
    );
  }
  /**
   * 移动树节点
   * @param fromIndex
   * @param toIndex
   */
  moveTreeNode(fromIndex, toIndex) {
    const { dataSource } = this.state;
    const oldParent = dataSource[fromIndex][TREE_PARENT];
    if (oldParent === dataSource[toIndex][TREE_PARENT]) {
      const children = oldParent ? oldParent.children : this.store.data;
      const fromIdx = children.indexOf(dataSource[fromIndex]);
      const toIdx = children.indexOf(dataSource[toIndex]);
      const item = children.splice(fromIdx, 1)[0];
      children.splice(toIdx, 0, item);
      this.setExpand(-1);
    } else {
      import_message.message.warning("只能交换同级节点").then();
    }
  }
  /**
   * 移动行数据
   * @param fromIndex
   * @param toIndex
   */
  moveRow(fromIndex, toIndex) {
    const newDataSource = this.state.dataSource.slice();
    const item = newDataSource.splice(fromIndex, 1)[0];
    newDataSource.splice(toIndex, 0, item);
    this.updateFlag = import_common.UpdateFlagEnum.RowUpdate;
    this.setDataSource(newDataSource, { updateRaw: false });
  }
  /**
   * 动态设置所有列信息
   * @param columns 列信息
   */
  setColumns(columns) {
    const items = import_util.util.isFunction(columns) ? columns(this.state.columns) : columns;
    this.setState({
      columns: this._loadColumnState(items)
    });
  }
  getState() {
    return this.state;
  }
  resetSelected(ds) {
    var _a;
    this.lastHighlightKey = this._lastHighlightRowIndex > -1 ? (_a = this.getRow(this._lastHighlightRowIndex)) == null ? void 0 : _a[this.getKeyField()] : void 0;
    this._lastHighlightRowIndex = -1;
    this._keyMap.clear();
    this._selectedKeys.clear();
    if (ds && this.props.checkbox) {
      const [cb, kf] = [this.getCheckBoxDataIndex(), this.getKeyField()];
      import_util.util.loopChildren({ children: ds }, (r) => {
        if (r[cb]) {
          r[kf] && this._selectedKeys.add(r[kf]);
        }
      });
    }
  }
  /**
   * 动态设置数据源
   * @param dataSource
   * @param updateRaw 是否更新原始数据
   * @param callback 回调
   */
  setDataSource(dataSource, options = {}) {
    const updateRaw = import_util.util.isBoolean(options) ? options : (options == null ? void 0 : options.updateRaw) ?? true;
    const udpateStore = (options == null ? void 0 : options.udpateStore) ?? true;
    const callback = import_util.util.isFunction(arguments[2]) ? arguments[2] : options == null ? void 0 : options.callback;
    const newDataSource = import_util.util.isFunction(dataSource) ? dataSource(this.store.data) : dataSource;
    if (this.state.dataSource !== newDataSource) {
      if (updateRaw) {
        this.store.raw = this.deepCopyRaw(newDataSource);
        this.resetSelected();
      }
      if (udpateStore || this.store.raw === this._defaultDs) {
        this.store.data = [];
        if (this.props.isTree) {
          newDataSource.forEach((r) => {
            if (r[TREE_LEVEL] === 1 || r[TREE_LEVEL] === void 0) {
              this.store.data.push(r);
            }
          });
        } else if (this.props.groupBy) {
          newDataSource.forEach((r) => {
            if (r[import_common.IS_GROUP]) {
              Array.prototype.push.apply(this.store.data, r.children);
            }
          });
        }
        if (!this.store.data.length) {
          this.store.data = newDataSource;
        }
        this.store.aggregateData = this.store.data;
        if (this.store.raw === this._defaultDs) {
          this.store.raw = this.deepCopyRaw(this.store.data);
        }
      }
      const newState = {
        dataSource: updateRaw ? this.generateDataSource((0, import_util.dataSortOrder)(newDataSource, this.state.orderBy, this.getDataIndexMap()), {}) : this.props.isTree ? this.generateDataSource(this.store.data, { level: 0 }) : newDataSource
      };
      this.updateFlag = this.updateFlag || import_common.UpdateFlagEnum.ForceUpdate;
      if (![import_common.UpdateFlagEnum.ColumnChecked, import_common.UpdateFlagEnum.RowUpdate].includes(this.updateFlag)) {
        newState.errors = {};
      }
      this._updateParentInfo(this.store.data);
      this.setState(newState, () => {
        var _a, _b;
        this.dsUpdateCallback = callback;
        if (this.updateFlag === import_common.UpdateFlagEnum.ForceUpdate) {
          (_b = (_a = this.props).onDataLoad) == null ? void 0 : _b.call(_a, this);
          this._observer.prevNotify({ table: this }, "onDataLoad").then();
        }
      });
    }
  }
  setSubDataSource(dataSource, parentRow) {
    var _a;
    if (((_a = this.parentInfo) == null ? void 0 : _a.data) !== parentRow.data) {
      this.parentInfo = parentRow;
      this.setDataSource(dataSource, { updateRaw: true });
    }
  }
  /**
   * 清空数据源的值
   * @param rowIndex 行索引，默认-1 清空所有行
   * @param nullValue 空值，默认为null
   */
  clearData(rowIndex = -1, nullValue = null) {
    const keyField = this.getKeyField();
    if (rowIndex > -1) {
      const newData = import_util.util.deepCopy(this.getRow(rowIndex), true);
      Object.keys(newData).forEach((key) => {
        keyField !== key && (newData[key] = nullValue);
      });
      this.updateRowDataByIndex(rowIndex, newData, false);
    } else {
      this.setDataSource(
        (ds) => {
          return ds.map((d) => {
            Object.keys(d).forEach((key) => {
              keyField !== key && (d[key] = nullValue);
            });
            return d;
          });
        },
        { updateRaw: false, udpateStore: false }
      );
    }
  }
  /**
   * 更新原数据行
   * @param row 原数据
   * @param flag
   */
  updateRow(row, flag = import_common.UpdateFlagEnum.UserUpdate) {
    if (!row)
      return;
    const rows = import_util.util.isArray(row) ? row : [row];
    if (rows.length === 0)
      return;
    const update = [];
    rows.forEach((r) => {
      var _a;
      if (!r.__update__ && flag !== import_common.UpdateFlagEnum.ColumnChecked) {
        let rIdx = this.getRowIndex(r);
        if (rIdx < 0) {
          rIdx = ((_a = this.state.selected) == null ? void 0 : _a.rowIndex) ?? -1;
          const oldR = r;
          r = this.getRow(rIdx);
          r && Object.assign(r, oldR);
        }
        if (rIdx === -1 || !r) {
          return;
        }
        r.__update__ = {
          rowIndex: rIdx
        };
      }
      update.push(r.__update__);
    });
    if (!update.length) {
      return;
    }
    this.updateFlag = flag;
    const single = update.length === 1;
    this.setDataSource([...this.state.dataSource], {
      udpateStore: false,
      updateRaw: false,
      callback: () => {
        if (flag !== import_common.UpdateFlagEnum.RowUpdate) {
          return;
        }
        this.notify(
          {
            updateRow: single ? rows[0] : rows,
            update: single ? update[0] : update,
            table: this,
            updateFlag: flag
          },
          "onUpdateRow"
        );
      }
    });
  }
  /**
   * 批量更新数据源
   * @param updateData 键值对
   */
  patchUpdate(updateData) {
    const keys = Object.keys(updateData);
    return new Promise((resolve) => {
      const update = [];
      this.updateFlag = import_common.UpdateFlagEnum.RowUpdate;
      this.setDataSource(
        (ds) => {
          return ds.map((r, rowIndex) => {
            keys.forEach((key) => {
              r[key] = updateData[key];
            });
            r.__update__ = { rowIndex };
            update.push(r.__update__);
            return r;
          });
        },
        {
          updateRaw: false,
          udpateStore: false,
          callback: (...args) => {
            this.notify(
              {
                updateRow: this.getRows(),
                update,
                table: this,
                updateFlag: import_common.UpdateFlagEnum.RowUpdate
              },
              "onUpdateRow"
            );
            resolve(args[0]);
          }
        }
      );
    });
  }
  /**
   * 按照行索引更新行数据
   * @param rowIndex
   * @param rowData
   * @param merge 是否合并原数据
   */
  updateRowDataByIndex(rowIndex, rowData, merge = true) {
    const newRow = this.getRow(rowIndex);
    const { dataIndexExpr } = this.generateColumns();
    if (newRow !== rowData) {
      if (!merge) {
        import_util.util.clearObject(newRow);
      }
      Object.assign(newRow, rowData);
    }
    if (newRow[GROUP_PARENT]) {
      newRow[GROUP_PARENT].children = [...newRow[GROUP_PARENT].children];
    }
    const update = newRow.__update__ || { rowIndex };
    newRow.__update__ = update;
    const { dataIndex } = update;
    if (merge && dataIndex) {
      const startIndex = Math.max(
        0,
        dataIndexExpr.findIndex((d) => d.dIdx === dataIndex)
      );
      const dataIndexExprLen = dataIndexExpr.length;
      for (let i = startIndex + 1; i < startIndex + dataIndexExpr.length; i++) {
        const { fn, exprType, expr, dIdx } = dataIndexExpr[i % dataIndexExprLen];
        if (fn && (exprType === "function" || expr.indexOf(`$R.${dataIndex}`) > -1)) {
          if (dIdx !== dataIndex)
            try {
              newRow[dIdx] = fn(newRow, this.state.dataSource, newRow[dIdx], dIdx);
            } catch {
            }
        }
      }
    }
    this.currentUpdateRow = newRow;
    this.updateFlag = import_common.UpdateFlagEnum.RowUpdate;
    this.setDataSource([...this.state.dataSource], {
      updateRaw: false,
      udpateStore: false,
      callback: () => {
        const value = {
          dataIndex,
          update,
          updateRow: newRow,
          table: this,
          updateFlag: import_common.UpdateFlagEnum.RowUpdate
        };
        this.notify(value, "onUpdateRow");
      }
    });
  }
  /**
   * 增加数据行
   * @param rows 需要增加的行数据
   * @param callback 增行回调
   * @param insertIndex 插入位置，默认行尾
   */
  addRows(rows = {}, insertIndex, callback) {
    return new Promise((resolve) => {
      var _a;
      const addRowArray = import_util.util.deepCopy(import_util.util.isArray(rows) ? rows : [rows]);
      if (((_a = this.parentInfo) == null ? void 0 : _a.data) === null) {
        import_message.message.warning("请先选择主表行!").then();
        resolve(false);
        return;
      }
      if (addRowArray.length === 0) {
        resolve(false);
        return;
      }
      const dataSource = [...this.getRows()];
      if (import_util.util.isNumber(callback)) {
        insertIndex = Number(callback);
        callback = void 0;
      }
      if (import_util.util.isNullOrEmpty(insertIndex)) {
        insertIndex = dataSource.length;
      }
      insertIndex = Math.min(Math.max(0, insertIndex || 0), dataSource.length);
      dataSource.splice(insertIndex, 0, ...addRowArray);
      const firstInsertRow = dataSource[insertIndex];
      let tmpIndex = 0;
      for (let i = 0, len = insertIndex; i <= len; i++) {
        if (firstInsertRow === dataSource[i]) {
          break;
        }
        if (!dataSource[i][TREE_PARENT]) {
          tmpIndex += 1;
        }
      }
      tmpIndex > -1 && this.store.data.splice(insertIndex, 0, ...addRowArray);
      this.updateFlag = import_common.UpdateFlagEnum.RowUpdate;
      this.setDataSource(dataSource, {
        updateRaw: false,
        udpateStore: false,
        callback: () => {
          callback ? callback({
            table: this,
            rowIndex: insertIndex
          }) : this.scrollToItem({ rowIndex: insertIndex, align: "smart" });
          resolve(true);
        }
      });
    });
  }
  /**
   * 增加子节点
   * @param parentRow
   * @param rows
   * @param insertIndex
   */
  addChildrenRow(parentRow, rows = {}, insertIndex) {
    const addRowArray = import_util.util.deepCopy(import_util.util.isArray(rows) ? rows : [rows]);
    if (parentRow) {
      if (parentRow.children) {
        insertIndex = Math.min(parentRow.children.length, insertIndex ?? Number.MAX_VALUE);
        parentRow.children.splice(insertIndex, 0, ...addRowArray);
      } else {
        parentRow.children = addRowArray;
      }
      this.setExpand(this.getRowIndex(parentRow));
    } else {
      this.addRows(rows, insertIndex).then();
    }
  }
  /**
   * 通过行索引删除数据行
   * @param rowIndexes 行索引
   */
  deleteRows(rowIndexes) {
    return new Promise((resolve) => {
      var _a;
      const deleteIndexArray = import_util.util.isArray(rowIndexes) ? rowIndexes : [rowIndexes];
      if (import_util.util.isNullOrEmpty(rowIndexes) || deleteIndexArray.length === 0) {
        return resolve(void 0);
      }
      const renderRows = this._renderDataSource || this.getRows();
      const deleteRows = deleteIndexArray.map((idx) => {
        return import_util.util.isNumber(idx) ? renderRows[idx] : idx;
      });
      const allRows = this.getRows();
      const dataSource = [];
      let existDeleteIndex = false;
      for (let i = allRows.length - 1; i >= 0; i--) {
        const data = allRows[i];
        if (deleteRows.indexOf(data) < 0 && (!data[TableSymbol.TREE_PARENT] || data[TableSymbol.TREE_PARENT].children)) {
          dataSource.unshift(data);
        } else {
          delete data.children;
          const pChildren = ((_a = data[TableSymbol.TREE_PARENT]) == null ? void 0 : _a.children) || this.store.data;
          if (pChildren) {
            pChildren.splice(pChildren.indexOf(data), 1);
          }
          existDeleteIndex = true;
        }
      }
      if (existDeleteIndex) {
        this.resetSelected();
        this.updateFlag = import_common.UpdateFlagEnum.ForceUpdate;
        this.setDataSource(dataSource, { updateRaw: false, udpateStore: false, callback: resolve });
      } else {
        resolve(void 0);
      }
    });
  }
  deleteRow(row) {
    return new Promise((resolve) => {
      if (!row)
        return resolve(void 0);
      const parentRow = row[TREE_PARENT];
      delete row.children;
      const children = parentRow ? parentRow.children : this.store.data;
      const deleteIndex = children.indexOf(row);
      if (deleteIndex > -1) {
        const expandIndex = parentRow ? this.getRowIndex(parentRow) : -1;
        children.splice(deleteIndex, 1);
        if (this.shouldResetStyleCacheOnItemSizeChange()) {
          this.setExpand(expandIndex, { callback: resolve });
        } else {
          this.updateFlag = import_common.UpdateFlagEnum.RowUpdate;
          this.setDataSource([...this.store.data], { updateRaw: false, udpateStore: false, callback: resolve });
        }
      } else {
        resolve(void 0);
      }
    });
  }
  /**
   * 删除所有数据行
   */
  clearRows() {
    return new Promise((resolve) => {
      this.setDataSource([], { updateRaw: false, udpateStore: true, callback: resolve });
    });
  }
  /**
   * 删除多选选中行
   */
  deleteCheckedRows() {
    return this.deleteRows(this.getCheckedIndexes());
  }
  deleteSelectedRows() {
    return this.deleteRows(this.getSelectedIndexes());
  }
  /**
   * 删除单选选中行
   */
  deleteSelectedRow() {
    return this.deleteRow(this.getSelectedRow());
  }
  /**
   * 滚动到单元格位置
   * @param rowIndex 行索引
   * @param columnIndex 列索引
   * @param dataIndex
   * @param align
   */
  scrollToItem({
    rowIndex,
    columnIndex,
    dataIndex,
    align
  }) {
    var _a, _b;
    if (dataIndex) {
      columnIndex = ((_a = this.getDataIndexMap()[dataIndex]) == null ? void 0 : _a.columnIndex) ?? columnIndex;
    }
    (_b = this.outRef.current) == null ? void 0 : _b.scrollToItem({
      rowIndex,
      columnIndex,
      align: align || "start"
    });
  }
  /**
   * 设置是否选中行
   * @param rowIndexes 行索引
   * @param selected true选中 false不选中
   */
  setSelected(rowIndexes, selected = true) {
    const dataIndex = this.getCheckBoxDataIndex();
    if (this.props.checkbox) {
      const selectedIndexArray = import_util.util.isArray(rowIndexes) ? rowIndexes : [rowIndexes];
      const allRows = this.getRows();
      const rows = [];
      selectedIndexArray.forEach((idx) => {
        const row = allRows[idx];
        if ((0, import_check.loopChildren)(this, row, dataIndex, selected, idx)) {
          if (!selected && idx === this._lastHighlightRowIndex) {
            this._lastHighlightRowIndex = -1;
          }
          rows.push(row);
        }
      });
      const checkedData = allRows.filter((r) => r[dataIndex] === true);
      this.onCheckedChange(checkedData, rows.length === 1 ? rows[0] : rows, selected);
    } else {
      if (!selected && rowIndexes !== this._lastHighlightRowIndex) {
        return;
      }
      setTimeout(() => {
        this.setHighlight(selected ? rowIndexes[0] ?? rowIndexes : -1);
      });
    }
  }
  /**
   * 切换行的选中状态
   * @param rowIndex 行索引
   * @private
   */
  switchSelected(rowIndex) {
    const dataIndex = this.getCheckBoxDataIndex();
    const row = this.getRow(rowIndex);
    this.setSelected(rowIndex, !row[dataIndex]);
  }
  /**
   * 判断行是否可以选中
   * @param row
   */
  isRowSelectionDisabled(row) {
    var _a, _b;
    return (_b = (_a = this.props.rowSelection) == null ? void 0 : _a.disabled) == null ? void 0 : _b.call(_a, row);
  }
  getKeyField(keyFieldName) {
    if (keyFieldName) {
      return this.props[keyFieldName];
    }
    return this.props.keyField || ROW_KEY_FIELD;
  }
  getExpandField() {
    return this.props.expandField || import_common.IS_EXPANDED;
  }
  _clearChecked() {
    if (this.props.checkbox) {
      const dataIndex = this.getCheckBoxDataIndex();
      const allRows = this.getRows();
      const updateRows = [];
      allRows.forEach((row, index) => {
        (0, import_check.loopChildren)(this, row, dataIndex, false, index, true, updateRows);
      });
      return updateRows;
    }
  }
  _setCheckedByRowSelection(rowIndex, checked, incompatible = false) {
    if (this.isMultipleInterval() && this.props.checkbox) {
      if (checked && incompatible) {
        this._clearChecked();
      }
      this.setSelected(rowIndex, checked);
      return true;
    }
    return false;
  }
  clearSelected() {
    this.resetSelected();
    const updateRows = this._clearChecked();
    this._observer.notify({}, "clearCacheCheckState");
    this.onCheckedChange([], updateRows, false);
  }
  /**
   * 是否多选一个或连续范围模式
   */
  isMultipleInterval() {
    var _a;
    const type = (_a = this.props.rowSelection) == null ? void 0 : _a.type;
    if (import_util.util.isArray(type)) {
      return type.includes(import_common.TableSelectionModel.MULTIPLE_INTERVAL);
    }
    return type === import_common.TableSelectionModel.MULTIPLE_INTERVAL;
  }
  /**
   * 设置高亮行索引
   * @param rowIndex
   * @param ctrlKey
   * @param shiftKey
   */
  setHighlight(rowIndex, { ctrlKey = false, shiftKey = false } = {}) {
    if (rowIndex === -1) {
      rowIndex = this._lastHighlightRowIndex;
      this._lastHighlightRowIndex = -1;
      this._selectedKeys.clear();
      if (rowIndex > -1) {
        this.notify({ rowIndex, table: this }, "clickHighlight");
      }
      return;
    }
    if (!this.isMultipleInterval()) {
      shiftKey = false;
      ctrlKey = false;
    }
    const [currentRow, keyField] = [this.getRow(rowIndex), this.getKeyField()];
    if (!currentRow) {
      return;
    }
    const keyValue = currentRow[keyField];
    if (ctrlKey) {
      if (this.isRowSelectionDisabled(currentRow)) {
        return;
      }
      if (this._selectedKeys.has(keyValue)) {
        this._lastHighlightRowIndex = -1;
        this._selectedKeys.delete(keyValue);
        this._setCheckedByRowSelection(rowIndex, false);
      } else {
        this._lastHighlightRowIndex = rowIndex;
        this._selectedKeys.add(keyValue);
        this._setCheckedByRowSelection(rowIndex, true);
      }
      this.notify({ rowIndex, table: this }, "clickHighlight");
    } else if (shiftKey) {
      const selectedRowIndex = [];
      for (let i = Math.min(this._lastHighlightRowIndex, rowIndex), max = Math.max(this._lastHighlightRowIndex, rowIndex); i <= max; i++) {
        const r = this.getRow(i);
        if (r && !this._selectedKeys.has(r[keyField]) && !this.isRowSelectionDisabled(r)) {
          this._selectedKeys.add(r[keyField]);
          selectedRowIndex.push(i);
        }
        this._lastHighlightRowIndex = rowIndex;
      }
      this._setCheckedByRowSelection(selectedRowIndex, true);
      this.notify({ rowIndex: selectedRowIndex, table: this }, "clickHighlight");
    } else {
      if (this.isRowSelectionDisabled(currentRow)) {
        return;
      }
      this._lastHighlightRowIndex = rowIndex;
      this._selectedKeys.clear();
      this._selectedKeys.add(keyValue);
      this._setCheckedByRowSelection(rowIndex, true, true);
      this.notify({ rowIndex, table: this }, "clickHighlight");
    }
  }
  onCheckedChange(checkedData, row, checked) {
    var _a, _b;
    (_b = (_a = this.props).onCheckedChange) == null ? void 0 : _b.call(_a, checkedData, row, checked);
    this.updateRow(row, import_common.UpdateFlagEnum.ColumnChecked);
    this.notify({ checkedData, row, checked, table: this }, "onCheckedChange");
  }
  /**
   * 获取当前高亮的数据行（单选数据行）
   */
  getSelectedRow() {
    if (this._selectedKeys.size > 0) {
      return this.getRowByKey(this._selectedKeys.values().next().value);
    }
    return this._lastHighlightRowIndex > -1 ? this.getRow(this._lastHighlightRowIndex) : null;
  }
  /**
   * 获取所有选中的行数据(优先返回checkbox选中的行数据, 如果没有多选则返回当前高亮选中的数据)
   */
  getSelectedData() {
    if (this.props.checkbox) {
      return this.getCheckedData();
    }
    const sd = [];
    this.getSelectedKeys().forEach((key) => {
      const row = this.getRowByKey(key);
      row && sd.push(row);
    });
    return sd;
  }
  /**
   * 多选模式的选中行
   */
  getSelectedIndexes() {
    if (this.props.checkbox) {
      return this.getCheckedIndexes();
    }
    if (this._selectedKeys.size > 0) {
      const checkedIndexes = [];
      const [keyField, allRows] = [this.getKeyField(), this.getRows()];
      allRows.forEach((row, index) => {
        if (this._selectedKeys.has(row[keyField])) {
          checkedIndexes.push(index);
        }
      });
      return checkedIndexes;
    }
    return [];
  }
  /**
   * 获取所有选中checkbox的行数据
   */
  getCheckedData() {
    var _a, _b;
    if ((_b = (_a = this.alertObj.state) == null ? void 0 : _a.selectedRows) == null ? void 0 : _b.length) {
      return this.alertObj.state.selectedRows;
    }
    const allRows = this.getRows();
    const dataIndex = this.getCheckBoxDataIndex();
    return dataIndex ? allRows.filter((r) => r[dataIndex] === true) : [];
  }
  /**
   * 获取当前高亮的行索引，小于0未选中（单选数据行索引）
   */
  getSelectedIndex() {
    return this._lastHighlightRowIndex < this.getRows().length ? this._lastHighlightRowIndex : -1;
  }
  /**
   * 获取当前高亮的行keys, onlyCurrentPage 只取当前页的选中状态
   */
  getSelectedKeys(onlyCurrentPage = false) {
    var _a, _b;
    const row = this.getRow(this._lastHighlightRowIndex);
    if (row) {
      const keyValue = row[this.getKeyField()];
      if (this._selectedKeys.size === 0) {
        keyValue !== void 0 && this._selectedKeys.add(keyValue);
        this._updateSubTable(row).then();
      } else {
        const selectedRow = this.getRowByKey(this._selectedKeys.values().next().value) || row;
        this._lastHighlightRowIndex = this.getRowIndex(selectedRow);
        this._updateSubTable(selectedRow).then();
      }
    } else {
      this._lastHighlightRowIndex = -1;
      this._updateSubTable(null).then();
    }
    return !onlyCurrentPage && ((_b = (_a = this.alertObj.state) == null ? void 0 : _a.selectedRowKeys) == null ? void 0 : _b.length) ? new Set(this.alertObj.state.selectedRowKeys) : this._selectedKeys;
  }
  /**
   * 获取所有选中checkbox的行索引
   */
  getCheckedIndexes() {
    const checkedIndexes = [];
    const allRows = this.getRows();
    const dataIndex = this.getCheckBoxDataIndex();
    if (dataIndex) {
      allRows.forEach((data, index) => {
        if (data[dataIndex]) {
          checkedIndexes.push(index);
        }
      });
    }
    return checkedIndexes;
  }
  getCheckBoxDataIndex() {
    const { checkbox } = this.props;
    const dataIndex = checkbox === true ? "checked" : checkbox;
    return dataIndex || DEFAULT_CHECKED;
  }
  /**
   * 返回编辑器对象暴露的api或属性
   * @param dataIndex
   */
  getEditor(dataIndex) {
    const {
      selected: { editing }
    } = this.state;
    const column = this.getDataIndexMap()[dataIndex];
    if (!column)
      return null;
    const editor = column.editor;
    return {
      getProps: () => ({ ...editor }),
      setProps: (options) => {
        if (import_util.util.isFunction(options)) {
          const n = options(editor);
          for (let key in editor) {
            if (editor.hasOwnProperty(key)) {
              delete editor[key];
            }
          }
          import_util.util.assign(editor, n);
        } else {
          if (options.antProps) {
            options.antProps = { ...editor.antProps, ...options.antProps };
          }
          import_util.util.assign(editor, options);
        }
        if (editing) {
          this.endEditing();
        }
      },
      addListener: (eventName, listener) => {
        const oldListeners = editor.listeners || {};
        const en = `on${import_util.util.toFirstUpperCase(eventName)}`;
        editor.listeners = {
          ...oldListeners,
          [en]: (...args) => {
            var _a;
            (_a = oldListeners[en]) == null ? void 0 : _a.call(oldListeners, ...args);
            listener(...args);
          }
        };
        if (editing) {
          this.endEditing();
        }
      }
    };
  }
  deepCopyRaw(obj) {
    if (this.props.cacheRaw) {
      this.rawData = obj;
      return new Promise((resolve) => {
        const cb = window.requestIdleCallback || window.requestAnimationFrame;
        cb(() => {
          this.rawData = import_util.util.deepCopy(obj, true);
          resolve(this.rawData);
        });
      });
    } else {
      this.rawData = [];
      return new Promise((resolve) => {
        this.rawData = [];
        resolve(this.rawData);
      });
    }
  }
  /**
   * 查询接口（服务端）
   * @param params 参数
   * @param onsuccess 回调
   */
  query(params, onsuccess, onfinally) {
    if (this.props.fullyControlled) {
      onfinally == null ? void 0 : onfinally();
      return;
    }
    let newParams = this.state.params;
    if (params) {
      newParams = import_util.util.isFunction(params) ? params(newParams) : { ...this.state.params, queryFilter: params };
    }
    const { queryFilter = {}, ...others } = newParams;
    this._queryPromise({ ...others, ...queryFilter }).then((res) => {
      var _a;
      if (this.unmount) {
        return;
      }
      onsuccess == null ? void 0 : onsuccess(res);
      const ds = res ? res.record ?? res.list ?? (import_util.util.isArray(res) ? res : []) : [];
      const dsChanged = ds !== this.store.data;
      this.store.aggregateData = ds;
      this.store.data = ds;
      this.store.raw = this.deepCopyRaw(ds);
      this.updateFlag = import_common.UpdateFlagEnum.ForceUpdate;
      const dataSource = this.generateDataSource((0, import_util.dataSortOrder)(ds, this.state.orderBy, this.getDataIndexMap()), {});
      if (dsChanged) {
        this.resetSelected();
        this._initDefaultSelected(dataSource);
        (_a = this.outRef.current) == null ? void 0 : _a.resetAfterRowIndex(0, false);
      }
      this.setState(
        {
          loading: this.props.loading ?? false,
          total: Number((res == null ? void 0 : res.total) ?? ds.length),
          aggregates: res.aggregates || {},
          summaryData: res.summaryData || {},
          dataSource,
          params: newParams,
          errors: {}
        },
        () => {
          var _a2, _b;
          (_b = (_a2 = this.props).onDataLoad) == null ? void 0 : _b.call(_a2, this);
          this._observer.prevNotify({ table: this }, "onDataLoad").then();
        }
      );
    }).finally(onfinally);
  }
  /**
   * 扩展参数查询列表
   * @param extraParam 扩展参数
   * @param autoLoad 是否自动加载
   */
  setExtraParam(extraParam, autoLoad = true) {
    if (this.props.fullyControlled) {
      return;
    }
    this._isPagination = Boolean(extraParam.__isPagination__);
    delete extraParam.__isPagination__;
    this.state.params = { ...this.state.params, ...extraParam };
    if (autoLoad) {
      this.query();
    }
  }
  /**
   * 按关键词过滤（前端）
   * @param keyword 关键词
   * @param dataIndexArr 过滤字段
   */
  filter(keyword, dataIndexArr = [], includeChildren = true) {
    let filterData = this.store.data;
    if (keyword) {
      const innerFilter = (predicate) => {
        if (this.props.isTree) {
          return import_util.util.filterTree(filterData, predicate, { includeChildren });
        }
        return filterData.filter(predicate);
      };
      if (import_util.util.isFunction(keyword)) {
        filterData = innerFilter(keyword);
      } else {
        if (!dataIndexArr || dataIndexArr.length === 0) {
          dataIndexArr = this.state.columns.map((c) => c.dataIndex);
        }
        filterData = innerFilter(
          (0, import_util.clientColumnFilter)(
            dataIndexArr.reduce((p, key) => {
              return { ...p, [key]: keyword };
            }, {}),
            this.getDataIndexMap(),
            false
          )
        );
      }
    }
    this.store.aggregateData = filterData;
    this.refreshView({
      state: {
        dataSource: this.generateDataSource((0, import_util.dataSortOrder)(filterData, this.state.orderBy, this.getDataIndexMap()))
      },
      rowColumnIndex: { rowIndex: 0 }
    });
  }
  /**
   * 查找关键词并定位
   * @param param
   */
  async findKeyword(param) {
    var _a, _b;
    const rows = this.getRows();
    const len = rows.length;
    if (import_util.util.isNullOrEmpty(param.keyword) || !param.dataIndex) {
      return [-1, len];
    }
    const { currentIndex = -1 } = param;
    const isTree = this.props.isTree;
    const keyword = import_util.util.isString(param.keyword) ? param.keyword.toLowerCase() : param.keyword;
    const dataIndexArray = import_util.util.isArray(param.dataIndex) ? param.dataIndex : [param.dataIndex];
    let rowIndex = -1;
    const dataIndexMap = this.getDataIndexMap();
    const isFind = (row) => {
      return dataIndexArray.some((dataIndex) => {
        const { filter } = dataIndexMap[dataIndex] || {};
        if (import_util.util.isFunction(filter == null ? void 0 : filter.clientFilter)) {
          return filter.clientFilter({ dataIndex, row, value: row[dataIndex], filterValue: param.keyword });
        }
        if (import_util.util.isString(keyword)) {
          const str = row[dataIndex] ? (row[dataIndex] + "").toLowerCase() : "";
          return str.includes(keyword);
        }
        if (import_util.util.isArray(keyword)) {
          return keyword.includes(row[dataIndex]);
        }
        return row[dataIndex] === keyword;
      });
    };
    let startIndex = currentIndex + 1;
    if (isTree && currentIndex > -1 && !rows[currentIndex][this.getExpandField()] && ((_a = rows[currentIndex].children) == null ? void 0 : _a.length)) {
      startIndex = currentIndex;
    }
    for (let i = startIndex; i < len; i++) {
      const row = rows[i];
      if (i > currentIndex && isFind(row)) {
        rowIndex = i;
        break;
      } else if (isTree && !row[this.getExpandField()] && ((_b = row.children) == null ? void 0 : _b.length)) {
        let findLevel = 0;
        import_util.util.loopChildren(
          row,
          (rr, _, level, count) => {
            if (isFind(rr)) {
              findLevel = level;
              rowIndex = count + i;
              return false;
            }
          },
          row[TREE_LEVEL]
        );
        if (rowIndex > -1) {
          await new Promise((resover) => {
            this.setExpand(i, { level: findLevel, callback: resover });
          });
          break;
        }
      }
    }
    if (rowIndex > -1) {
      this.scrollToItem({ rowIndex, align: "smart" });
      this.setHighlight(rowIndex);
    } else if (currentIndex > -1) {
      return this.findKeyword({ ...param, currentIndex: -1 });
    }
    return [rowIndex, this.getRows().length];
  }
  /**
   * 刷新接口
   */
  refreshData({ toFirst = false } = {}) {
    return new Promise((resolve) => {
      if (this.props.checkbox) {
        this._lastHighlightRowIndex = -1;
      }
      this.query(
        (params) => {
          return toFirst ? { ...params, pageIndex: 1 } : params;
        },
        void 0,
        (result) => {
          this._observer.notify({}, "clearCacheCheckState");
          resolve(result);
        }
      );
    });
  }
  refreshRowHeight(immediate = false) {
    this._resetRowHeight({ immediate });
  }
  /**
   * 刷新视图
   */
  refreshView(params = {}) {
    const { state, rowColumnIndex, cacheState = false, endEditing = false, callback } = params;
    const newState = import_util.util.isFunction(state) ? state(this.state) : state;
    Promise.resolve().then(() => {
      var _a, _b, _c;
      let { rowIndex, columnIndex } = rowColumnIndex || {};
      if (columnIndex !== void 0 || rowIndex !== void 0) {
        if (rowIndex === void 0) {
          (_a = this.outRef.current) == null ? void 0 : _a.resetAfterColumnIndex(columnIndex, false);
        } else if (columnIndex === void 0) {
          (_b = this.outRef.current) == null ? void 0 : _b.resetAfterRowIndex(rowIndex, false);
        } else {
          (_c = this.outRef.current) == null ? void 0 : _c.resetAfterIndices({
            rowIndex,
            columnIndex,
            shouldForceUpdate: false
          });
        }
      }
      this.setState(
        {
          ...newState,
          selected: endEditing ? { ...this.state.selected, rowIndex: -1, editing: false } : this.state.selected,
          updateTime: (/* @__PURE__ */ new Date()).valueOf()
        },
        () => {
          columnIndex !== void 0 && cacheState && this._saveColumnState();
          callback == null ? void 0 : callback();
        }
      );
    });
  }
  /**
   * 通过dataIndex设置列属性
   * @param dataIndex
   * @param props
   */
  setColumnProps(dataIndex, props) {
    this.refreshView({
      state: () => {
        const { columns } = this.state;
        const findColumn = columns.find((c) => c.dataIndex === dataIndex);
        if (findColumn) {
          import_util.util.assign(findColumn, import_util.util.isFunction(props) ? props(findColumn) : props);
          return { columns: [...columns] };
        }
        return { columns };
      },
      rowColumnIndex: {
        columnIndex: 0
      }
    });
  }
  getRenderRange() {
    var _a;
    return ((_a = this.outRef.current) == null ? void 0 : _a._rangeToRender) || { rowIndex: [0, 0], columnIndex: [0, 0] };
  }
  render() {
    this.updateStateByProps();
    const {
      className = "",
      bordered,
      editCellHighlight = false,
      compact,
      tabIndex,
      style = {},
      resizeDelay = 16,
      tableAlertRender,
      pagination,
      keyField
    } = this.props;
    const gc = this.generateColumns();
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        id: this.getId(false),
        ref: this.containerRef,
        style: { ...style, padding: 0, margin: 0 },
        tabIndex,
        className: import_util.util.classNames("virtual-table", className, {
          "edit-cell-highlight": !!editCellHighlight,
          "table-bordered": !!bordered,
          "table-compact": !!compact
        })
      },
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          style: {
            display: "flex",
            flexDirection: "column",
            height: "100%"
          }
        },
        tableAlertRender && pagination && keyField && /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            key: "alert",
            ref: (container) => {
              this.alertObj.container = container;
            },
            style: { zIndex: 3 }
          }
        ),
        /* @__PURE__ */ import_react.default.createElement("div", { key: "table", className: "table-ctx", style: { flex: 1, minHeight: 0, position: "relative" } }, /* @__PURE__ */ import_react.default.createElement(import_widgets.AutoResize, { onResize: this._onResize, delay: resizeDelay, beforeResize: this._onBeforeResize }, /* @__PURE__ */ import_react.default.createElement(TableGrid, { columns: gc, state: this.state, props: this.props, table: this }), /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { spinning: this.state.loading, className: "mask-loading" })))
      )
    );
  }
};
// 设置默认属性
TableClass.defaultProps = defaultProps;
function InnerTable({ outRef, ...cmpProps }) {
  var _a;
  const newProps = (0, import_util.syncDefaultProps)({ ...cmpProps });
  const {
    dataSource,
    request,
    pagination,
    rowSelection,
    onContextMenu,
    cache = ["column"],
    autoLoad = true,
    rowFilter
  } = newProps;
  const dataRequest = import_react.default.useCallback(
    ({ columnFilters = {} }, ins) => {
      const filterKey = Object.keys(columnFilters);
      const dataIndexMap = ins.getDataIndexMap() || {};
      return filterKey.length > 0 ? dataSource.filter((0, import_util.clientColumnFilter)(columnFilters, dataIndexMap)) : dataSource;
    },
    [dataSource]
  );
  if (!request && dataSource && pagination) {
    newProps.request = dataRequest;
    newProps.loading = newProps.loading;
    delete newProps.dataSource;
  }
  if ((_a = newProps.style) == null ? void 0 : _a.minHeight) {
    newProps.virtualScrolling = false;
  }
  if (onContextMenu) {
    newProps.rowContextMenu = onContextMenu;
    delete newProps.onContextMenu;
  }
  (0, import_util.useAsyncEffect)(async () => {
    if (autoLoad && newProps.request) {
      await outRef.current.refreshData();
    }
  }, [newProps.request, autoLoad]);
  (0, import_react.useLayoutEffect)(() => {
    var _a2;
    if (newProps.borderColor) {
      (_a2 = outRef.current) == null ? void 0 : _a2.containerRef.current.style.setProperty("--border-color-split", newProps.borderColor);
    }
  }, [newProps.borderColor]);
  if (newProps.rowFilter && import_util.util.isString(newProps.rowFilter)) {
    if (outRef.current && !outRef.current._rowFilter) {
      outRef.current._rowFilter = () => false;
    } else {
      newProps.rowFilter = () => false;
    }
  }
  (0, import_react.useEffect)(() => {
    var _a2;
    if (rowFilter && import_util.util.isString(rowFilter)) {
      const arr = rowFilter.split(".");
      if (arr.length > 1) {
        return (_a2 = import_util.util.getCmpApi(arr[0])) == null ? void 0 : _a2.subscribe(({ rowIndex, table }) => {
          const mainRow = table.getRow(rowIndex);
          outRef.current._rowFilter = (row) => {
            return mainRow[arr[1]] === row[arr[2] || arr[1]];
          };
          outRef.current.refreshData();
        }, "clickHighlight");
      }
    }
  }, [rowFilter]);
  if (rowSelection) {
    let { type, checkedField } = rowSelection;
    type = import_util.util.isArray(type) ? type : [type];
    if (type.includes(import_common.TableSelectionModel.CHECKBOX)) {
      newProps.checkbox = checkedField || true;
      if (type.includes(import_common.TableSelectionModel.ROW)) {
        newProps.rowChecked = true;
      }
    }
    if (type.includes(import_common.TableSelectionModel.ROW) || type.includes(import_common.TableSelectionModel.MULTIPLE_INTERVAL)) {
      newProps.rowSelected = true;
    }
    if (type.includes(import_common.TableSelectionModel.MULTIPLE_INTERVAL)) {
      newProps.rowChecked = false;
    }
    if (rowSelection.keyField) {
      newProps.keyField = rowSelection.keyField;
    }
    newProps.rowSelection = { ...rowSelection, type };
  }
  if (cache === true) {
    newProps.cache = ["selected", "column", "page"];
  } else if (cache === false) {
    newProps.cache = [];
  } else {
    newProps.cache = cache;
  }
  newProps.remember = newProps.cache.includes("column");
  return /* @__PURE__ */ import_react.default.createElement(TableClass, { ...newProps, ref: outRef });
}
var Table = (0, import_util.compHoc)(InnerTable, "");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  Table,
  TableSelectionModel,
  TableSymbol
});
